110,536
社区成员
发帖
与我相关
我的任务
分享
public Socket newsock;
public IPEndPoint localEP;
int recv;
string data1;
....
setPort = int.Parse("4450");
byte[] data = new byte[1024];
//初始化SOCKET实例
newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
localEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), setPort);//setPort 是端口 4450
newsock.Bind(localEP);
EndPoint Remote = (EndPoint)(localEP);
data = new byte[1024];
//接受信息
recv = newsock.ReceiveFrom(data, ref Remote);//跟进去就是这里异常
data1 = Encoding.UTF8.GetString(data, 0, recv).ToString();
发送端:
Socket Send;
//初始化C#Socket发送
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port1); //port1这个参数是端口 int ;
Send = new Socket(ipPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
Send.SendTo(Encoding.ASCII.GetBytes("要发送的消息"), ipPoint);//注意编码
接收端:
一直接收的话 需要开一个线程:
using System.Threading;//线程
public Thread myThread;
myThread = new Thread(RunsOnWorkerThread);
myThread.Start();//启动这个线程 //myThread.Abort();//关闭线程
private void RunsOnWorkerThread()
{Socket newsock; //声明一个Socket实例;
byte[] data = new byte[1024];
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), StrPortB); //IP 端口;
EndPoint Remote = (EndPoint)(ipPoint);
newsock = new Socket(ipPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);//初始化;
newsock.Bind(ipPoint);//绑定;
while (true)
{
try
{
newsock.ReceiveFrom(data, ref Remote);//读取接收的数据
data1 = Encoding.ASCII.GetString(data).ToString();
//textBox1.Text = data1;
}
Thread.Sleep(80);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
}