当前位置: 移动技术网 > IT编程>开发语言>c# > c# socket编程udp客户端实现代码分享

c# socket编程udp客户端实现代码分享

2019年07月18日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下: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();

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网