c# socket编程udp客户端实现代码分享
程序员文章站
2024-02-23 08:29:46
复制代码 代码如下:console.writeline("this is a client, host name is {0}", dns.gethostname());/...
复制代码 代码如下:
console.writeline("this is a client, host name is {0}", dns.gethostname());
//设置服务端终结点
ipendpoint ipe = new ipendpoint(ipaddress.parse("127.0.0.1"), 8001);
//创建与服务端连接的套接字,指定网络类型,数据连接类型和网络协议
socket connsocket = new socket(addressfamily.internetwork, sockettype.dgram, protocoltype.udp);
string welcome = "client message:hello!!!";
byte[] data = new byte[1024];
data = encoding.ascii.getbytes(welcome);
//给服务端发送测试消息
connsocket.sendto(data, data.length, socketflags.none, ipe);
ipendpoint server = new ipendpoint(ipaddress.any, 0);
//服务端终结点
endpoint remote = (endpoint)server;
data = new byte[1024];
//对于不存在的ip地址,加入此行代码后,可以在指定时间内解除阻塞模式限制
//server.setsocketoption(socketoptionlevel.socket, socketoptionname.receivetimeout, 100);
int recv = connsocket.receivefrom(data, ref remote);
//打印从服务端发回的信息
console.writeline("message received from {0}: ", remote.tostring());
console.writeline(encoding.ascii.getstring(data, 0, recv));
while (true) //可以实时给服务端发送消息
{
string input = console.readline();
if (input == "exit") //中断连接
{
connsocket.sendto(encoding.ascii.getbytes(input), remote);
data = new byte[1024];
recv = connsocket.receivefrom(data, ref remote);
console.writeline(encoding.ascii.getstring(data, 0, recv));
break;
}
else
{
connsocket.sendto(encoding.ascii.getbytes("client message:" + input), remote);
data = new byte[1024];
recv = connsocket.receivefrom(data, ref remote);
console.writeline(encoding.ascii.getstring(data, 0, recv));
}
}
console.writeline("stopping client.");
connsocket.close();