C#中Socket通信用法实例详解
程序员文章站
2022-06-30 10:22:08
本文实例讲述了c#中socket通信用法。分享给大家供大家参考。具体如下:
一、udp方式:
服务器端代码:
static void main(string[...
本文实例讲述了c#中socket通信用法。分享给大家供大家参考。具体如下:
一、udp方式:
服务器端代码:
static void main(string[] args) { int recv; byte[] data = new byte[1024]; ipendpoint ipep = new ipendpoint(ipaddress.any, 9050);//定义一网络端点 socket newsock = new socket(addressfamily.internetwork, sockettype.dgram, protocoltype.udp);//定义一个socket newsock.bind(ipep);//socket与本地的一个终结点相关联 console.writeline("waiting for a client.."); ipendpoint sender = new ipendpoint(ipaddress.any, 0);//定义要发送的计算机的地址 endpoint remote = (endpoint)(sender);// recv = newsock.receivefrom(data, ref remote);//接受数据 console.writeline("message received from{0}:", remote.tostring()); console.writeline(encoding.ascii.getstring(data, 0, recv)); string welcome = "welcome to my test server!"; data = encoding.ascii.getbytes(welcome); newsock.sendto(data, data.length, socketflags.none, remote); while (true) { data = new byte[1024]; recv = newsock.receivefrom(data, ref remote); console.writeline(encoding.ascii.getstring(data, 0, recv)); newsock.sendto(data, recv, socketflags.none, remote); } }
客户端代码:
void maininfo() { byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区 string input, stringdata; ipendpoint ipep = new ipendpoint(ipaddress.parse("192.168.1.21"), 9050); socket server = new socket(addressfamily.internetwork, sockettype.dgram, protocoltype.udp); string welcome = "hello,are you there?"; data = encoding.ascii.getbytes(welcome); server.sendto(data, data.length, socketflags.none, ipep);//将数据发送到指定的终结点 ipendpoint sender = new ipendpoint(ipaddress.any, 0); endpoint remote = (endpoint)sender; data = new byte[1024]; int recv = server.receivefrom(data, ref remote);//接受来自服务器的数据 console.writeline("message received from{0}:", remote.tostring()); console.writeline(encoding.ascii.getstring(data, 0, recv)); while (true)//读取数据 { input = richtextbox1.text;//从键盘读取数据 if (input == "text")//结束标记 { break; } server.sendto(encoding.ascii.getbytes(input), remote);//将数据发送到指定的终结点remote data = new byte[1024]; recv = server.receivefrom(data, ref remote);//从remote接受数据 stringdata = encoding.ascii.getstring(data, 0, recv); console.writeline(stringdata); } console.writeline("stopping client"); server.close(); }
二、tcp方式:
服务器端代码:
socket serversocket = null; thread clientthread = null; socket clientsocket = null; thread thread = null; ipaddress ips = null; pendpoint ipep = null; void serverstart() { ips = dns.gethostaddresses(dns.gethostname())[0]; //创建ipendpoint实例 ipep = new ipendpoint(ips, 9050); //创建一个套接字 serversocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); serversocket.setsocketoption(socketoptionlevel.socket, socketoptionname.reuseaddress, true); //将所创建的套接字与ipendpoint绑定 serversocket.bind(ipep); //设置套接字为收听模式 serversocket.listen(20); while (listenalive) { try { //在套接字上接收接入的连接 clientsocket = serversocket.accept(); clientthread = new thread(new parameterizedthreadstart(receivedata)); clientthread.start(clientsocket); } catch (exception ex) { writeerrorlog(ex.message); serversocket.close(); serversocket = null; } } } static void receivedata(object obj) { bool keepalive = true; socket s = obj as socket; byte[] buffer = new byte[1024]; //根据收听到的客户端套接字向客户端发送信息 ipendpoint clientep = (ipendpoint)s.remoteendpoint; console.writeline("客户端ip:" + clientep.address + " 端口:" + clientep.port); string welcome = "连接服务器成功"; buffer = system.text.encoding.unicode.getbytes(welcome); //向客户端发送“连接服务器成功”消息 s.send(buffer, buffer.length, socketflags.none); buffer = new byte[1024]; int buflen = 0; string content = string.empty; while (true) { //在套接字上接收客户端发送的信息 buflen = 0; try { buflen = s.receive(buffer); if (buflen == 0) { break; } content += system.text.encoding.unicode.getstring(buffer, 0, buflen); } catch (exception ex) { break; ; } } send(s, content); s = null; buffer = null; clientep = null; thread.currentthread.abort(); }
客户端代码:
void send(string content) { byte[] data = new byte[1024]; newclient = new system.net.sockets.socket(system.net.sockets.addressfamily.internetwork, system.net.sockets.sockettype.stream, system.net.sockets.protocoltype.tcp); ie = new system.net.ipendpoint(system.net.ipaddress.parse(ipadd), port);//服务器的ip和端口 try { //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的ip和端口。不需要监听。 newclient.connect(ie); } catch (system.net.sockets.socketexception e) { console.writeline(e.tostring()); return; } int recv = newclient.receive(data); //连接服务器成功 string stringdata = system.text.encoding.unicode.getstring(data, 0, recv); if (stringdata == "连接服务器成功") { newclient.send(system.text.encoding.unicode.getbytes(content)); newclient.shutdown(system.net.sockets.socketshutdown.send); data = new byte[1024]; recv = newclient.receive(data); string result = system.text.encoding.unicode.getstring(data, 0, recv); newclient.shutdown(system.net.sockets.socketshutdown.receive); newclient.close(); messagebox.show(result); } else { messagebox.show("连接服务器失败", "友情提示"); } }
希望本文所述对大家的c#程序设计有所帮助。
上一篇: 网络编程(UDP,TCP)