Socket代码
服务器端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading; namespace DMServer
{
public partial class Form1 : Form
{
Thread TempThread;
Socket server; string labelText = string.Empty; public string LabelText
{
get { return labelText; }
set
{
labelText = value;
}
} public static ManualResetEvent allDone = new ManualResetEvent(false); bool isDo = false; public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ } /// <summary>
/// 用这个方法,另一个经测试是不好使的
/// </summary>
public void StartReceive()
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
bool isGo = true;
server.Bind(new IPEndPoint(IPAddress.Parse("192.168.10.128"), )); //这里要写客户端访问的地址
server.Listen();
Box box = new Box();
while (isGo)
{
try
{
Socket s = server.Accept();
string content = string.Empty;
byte[] bs = new byte[s.Available]; int num = s.Receive(bs); content += Encoding.ASCII.GetString(bs); s.Send(Encoding.ASCII.GetBytes("ok"));
if (content.Equals("ABCD123"))
{
isGo = false;
}
}
catch (Exception ex)
{ } } server.Close();
} /// <summary>
/// 不好使
/// </summary>
public void StartReceive1()
{
server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), ));
server.Listen();
Box box = new Box();
box.WorkSocket = server;
while (true)
{
allDone.Reset();
server.BeginAccept(new AsyncCallback(ConnClient), box);
allDone.WaitOne();
}
} public void ConnClient(IAsyncResult ar)
{
Socket socket = ((Box)ar.AsyncState).WorkSocket;
Socket client = socket.EndAccept(ar); Box box = new Box();
box.WorkSocket = client; client.BeginReceive(box.Bytes, , box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
} public void Receive(IAsyncResult ar)
{
string content = string.Empty; Box box = (Box)ar.AsyncState; Socket handler = box.WorkSocket; int byteread = handler.EndReceive(ar); if (byteread > )
{
box.Bulider.Append(Encoding.ASCII.GetString(box.Bytes, , byteread)); content = box.Bulider.ToString(); if (content.IndexOf("") > -)
{
Send(handler, "ok");
}
else
{
handler.BeginReceive(box.Bytes, , box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
}
}
} private static void Send(Socket handler, String data)
{
// 消息格式转换.
byte[] byteData = Encoding.ASCII.GetBytes(data); // 开始发送数据给远程目标.
handler.BeginSend(byteData, , byteData.Length, ,
new AsyncCallback(SendCallback), handler);
} private static void SendCallback(IAsyncResult ar)
{ // 从state对象获取socket.
Socket handler = (Socket)ar.AsyncState; //完成数据发送
int bytesSent = handler.EndSend(ar); handler.Shutdown(SocketShutdown.Both);
handler.Close();
} private void button2_Click(object sender, EventArgs e)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect(IPAddress.Parse("192.168.10.128"), );
socket.Send(Encoding.ASCII.GetBytes("ABCD123"));
}
catch (Exception ex)
{ }
socket.Close();
} private void button1_Click(object sender, EventArgs e)
{
TempThread = new Thread(new ThreadStart(StartReceive));
TempThread.Start();
}
}
}
客户端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets; namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
IPAddress ip = IPAddress.Parse("192.168.10.128"); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try
{
client.Connect(ip, ); }
catch (Exception ex)
{
MessageBox.Show("连接失败!");
return;
} try
{
client.Send(Encoding.ASCII.GetBytes(this.textBox1.Text));
}
catch (Exception)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
return;
} Box box = new Box(); box.WorkSocket = client; client.BeginReceive(box.Bytes, , box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
} public void Receive(IAsyncResult ar)
{
string content = string.Empty; Box box = (Box)ar.AsyncState; Socket client = box.WorkSocket; int length = client.EndReceive(ar); if (length > )
{
box.Builder.Append(Encoding.ASCII.GetString(box.Bytes, , length)); content = box.Builder.ToString(); if (content.IndexOf("") > -)
{
MessageBox.Show(content);
client.Close();
}
else
{
client.BeginReceive(box.Bytes, , box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
}
}
} public class Box
{
Socket workSocket; public Socket WorkSocket
{
get { return workSocket; }
set { workSocket = value; }
} byte[] bytes = new byte[]; public byte[] Bytes
{
get { return bytes; }
set { bytes = value; }
} StringBuilder builder = new StringBuilder(); public StringBuilder Builder
{
get { return builder; }
set { builder = value; }
}
} private void Form1_Load(object sender, EventArgs e)
{ }
}
}
实际应用服务器端的开启方法,注意进程休眠的位置是为了解决运行太快接受不到传过来的数据的问题:
public void Start(object port)
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
bool isGo = true;
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[];
server.Bind(new IPEndPoint(ip, int.Parse(port.ToString())));
server.Listen();
while (isGo)
{
try
{
s = server.Accept();
Thread.Sleep(); //这里要注意,服务器端休眠的时间一定要比客户端少,否则和客户端一样或者大会导致客户端接收不到数据,不休眠自己会接收不到数据。
s.SendTimeout = ;
string content = "";
byte[] bytes = new byte[s.Available];
int num = s.Receive(bytes, , bytes.Length, SocketFlags.None); content = Encoding.UTF8.GetString(bytes); if (content.Equals("conn"))
{
s.Send(Encoding.UTF8.GetBytes("Data Source=" + ip.ToString() + ";Initial Catalog=DM;Persist Security Info=True;User ID=dm;Password=dm"));
}
if (content.Equals("Close"))
{
isGo = false;
}
}
catch (Exception ex)
{ }
}
s.Close();
server.Close();
}
这是修改后的客户端接受代码:
private void button1_Click(object sender, EventArgs e)
{
IPAddress ip = IPAddress.Parse("192.168.10.128"); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try
{
client.Connect(ip, ); }
catch (Exception ex)
{
MessageBox.Show("连接失败!");
return;
} try
{
client.Send(Encoding.UTF8.GetBytes(this.textBox1.Text));
}
catch (Exception)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
return;
}
string content = string.Empty;
int num = ;
Thread.Sleep();
byte[] b = new byte[client.Available];
num = client.Receive(b, , b.Length, SocketFlags.None);
content = Encoding.UTF8.GetString(b);
MessageBox.Show(content);
client.Close();
client.Dispose();
}
Socket代码的更多相关文章
- Netty实现的一个异步Socket代码
本人写的一个使用Netty实现的一个异步Socket代码 package test.core.nio; import com.google.common.util.concurrent.ThreadF ...
- SSL握手通信详解及linux下c/c++ SSL Socket代码举例
SSL握手通信详解及linux下c/c++ SSL Socket代码举例 摘自:http://www.169it.com/article/3215130236.html 分享到:8 发布时 ...
- SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码)
SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码) 摘自: https://blog.csdn.net/sjin_1314/article/det ...
- 网络编程之Socket代码实例
网络编程之Socket代码实例 一.基本Socket例子 Server端: # Echo server program import socket HOST = '' # Symbolic name ...
- 简单的 socket 代码
TCP 编程 客户端代码 将键盘输入的字符发送到服务端,并将从服务端接收到的字符输出到终端 #!/usr/python3 import socket def socket_client(): s = ...
- socket 代码实例
1. TCP SOCKET 客户端: #!/usr/bin/env python # -*-coding:utf-8 -*- import socket HOST = 'localhost' PO ...
- python入门之socket代码练习
Part.1 简单的socket单次数据传输 服务端: #服务器端 import socket server = socket.socket() # 声明socket类型,同时生成socket连接对象 ...
- 完整的Socket代码
先上图 列举一个通信协议 网关发送环境数据 此网关设备所对应的所有传感器参数,格式如下: 网关发送: 包长度+KEY值+请求类型+发送者+接收者+消息类型+消息内容 说明: 包长度:short int ...
- Python全栈开发:socket代码实例
客户端与服务端交互的基本流程 服务端server #!/usr/bin/env python # -*- coding;utf-8 -*- import socket sk = socket.sock ...
随机推荐
- Pandas排序
Pandas有两种排序方式,它们分别是 - 按标签 按实际值 下面来看看一个输出的例子. import pandas as pd import numpy as np unsorted_df=pd.D ...
- xp_sp3_pro_简中_x86_cd_vl_x14-74070
1.镜像文件: zh-hans_windows_xp_professional_with_service_pack_3_x86_cd_vl_x14-74070.iso 来自 msdn itellyou ...
- python学习笔记(接口自动化框架 V2.0)
这个是根据上次框架版本进行的优化 用python获取excel文件中测试用例数据 通过requets测试接口.并使用正则表达式验证响应信息内容 生成xml文件测试报告 版本更新内容: 1. 整理了Cr ...
- Ceph Monitor基础架构与模块详解
转自:https://www.ustack.com/blog/ceph-monitor/ Ceph rados cluster离不开Monitor,如果没有Monitor,则Ceph将无法执行一条简单 ...
- js获取一周的日期范围
function getWeek() { this.nowTime = new Date(); this.init = function() { this.dayInWeek = this.nowTi ...
- String、StringBuffer、StringBuilder分析(jdk8)
以下代码只挑选了关键方法进行分析 public final class String //String类不可继承,实现了序列化 implements java.io.Serializable, Com ...
- CSS: Flexbox
Use flexbox to create a responsive website, containing a flexible navigation bar and flexible conten ...
- mac上安装mongoDb以及简单使用
年初粗略学习了下node,这好几个月没玩,突然发现已经忘完了,还是简单记录下基本知识,方便再次使用时资料查找. 一.mongoDb安装 在mac上安装了brew的情况下,可以直接执行命令 brew i ...
- Golang调用windows下的dll动态库中的函数
Golang调用windows下的dll动态库中的函数 使用syscall调用. package main import ( "fmt" "syscall" & ...
- 拦截器springmvc防止表单重复提交【2】
[参考博客:http://my.oschina.net/mushui/blog/143397] 原理:在新建页面中Session保存token随机码,当保存时验证,通过后删除,当再次点击保存时由于服务 ...