winform客户端实现监控本机端口实现数据的发送和接收
代码语言:javascript
复制 #region 无连接给本机端口发送消息
public void local() {
byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区
string stringData;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("172.23.13.36"), 8082);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EndPoint ep2 = (EndPoint)ipep;
server.Bind(ipep);
string welcome = "Hello,are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);//将数据发送到指定的终结点
IPEndPoint sender = new IPEndPoint(IPAddress.Parse("172.23.13.36"), 8082);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
stringData = Encoding.ASCII.GetString(data, 0, recv);
server.Close();
}
#endregion
#region 有连接给本机端口发送消息
public void haveConnect()
{
byte[] data = new byte[1024];
IPEndPoint ie = new IPEndPoint(IPAddress.Parse("172.23.13.36"), 8082);//服务器的IP和端口
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(ie); //绑定IP地址:端口
//serverSocket.Listen(50); //设定最多10个排队连接请求
//构造定时器,时间间隙为1秒,即每隔一秒执行一次accept()方法,以获取连接请求队列中//第一个挂起的连接请求
serverSocket.Connect(ie);
string welcome = "Hello,are you there?";
data = Encoding.ASCII.GetBytes(welcome);
serverSocket.SendTo(data, data.Length, SocketFlags.None, ie);//将数据发送到指定的终结点
IPEndPoint sender = new IPEndPoint(IPAddress.Parse("172.23.13.36"), 8082);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = serverSocket.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
String stringData = Encoding.ASCII.GetString(data, 0, recv);
serverSocket.Close();
}
#endregion