C#最基本的Socket编程
程序员文章站
2022-07-04 22:24:24
示例程序是同步套接字程序,功能很简单,只是客户端发给服务器一条信息,服务器向客户端返回一条信息,是一个简单示例,也是一个最基本的socket编程流程。 简单步骤说明: 1.用指定的port, ip 建立一个EndPoint对象 2.建立一个Socket对象; 3.用Socket对象的Bind()方法 ......
示例程序是同步套接字程序,功能很简单,只是客户端发给服务器一条信息,服务器向客户端返回一条信息,是一个简单示例,也是一个最基本的socket编程流程。
简单步骤说明:
1.用指定的port, ip 建立一个endpoint对象
2.建立一个socket对象;
3.用socket对象的bind()方法绑定endpoint
4.用socket对象的listen()方法开始监听
5.接收到客户端的连接,用socket对象的access()方法创建新的socket对象用于和请求的客户端进行通信
6.通信结束后记得关闭socket
代码:
1 int port = 2000; 2 string host = "127.0.0.1"; 3 // create endpoint 4 ipaddress ip = ipaddress.parse(host); 5 ipendpoint ipe = new ipendpoint(ip, port); 6 socket s = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); 7 s.bind(ipe); 8 9 s.listen(0); 10 11 console.writeline("wait a client to connect.."); 12 socket temp = s.accept(); 13 console.writeline("create a connection"); 14 15 //receive message 16 string recvstr = ""; 17 byte[] recvbytes= new byte[1024]; 18 int bytes; 19 bytes = temp.receive(recvbytes, recvbytes.length, 0); 20 recvstr += encoding.ascii.getstring(recvbytes, 0, bytes); 21 console.writeline("server have get message:{0}",recvstr ); 22 23 // send message 24 string sendstr = "ok! client send message cuccessful"; 25 byte[] bs = encoding.ascii.getbytes(sendstr); 26 temp.send(bs, bs.length, 0); 27 28 //end 29 temp.close(); 30 s.close(); 31 32 console.writeline("end socket com!"); 33 console.readline();
客户端:
1.用指定的port, ip 建立一个endpoint对象
2.建立一个socket对象
3.用socket对象的connect()方法以上面的endpoint对象作为参数,向服务器发送连接请求;
4.如果连接成功,就用socket对象的send()方法向服务器发送信息
5.用socket对象的receive()方法接收服务器发来的信息
6.通信结束记得关闭socket:
代码::
//init server port and ip int port = 2000; string host = "127.0.0.1"; ipaddress ip = ipaddress.parse(host); // create ipendpoint ipendpoint ipe = new ipendpoint(ip, port); // create client sockets socket c = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); console.writeline("connecting..."); // connect to server c.connect(ipe); // send to server string sendstr = "hello, this is a socket test"; byte[] bs = encoding.ascii.getbytes(sendstr); console.writeline("send message"); c.send(bs, bs.length, 0); // receive a message from server string recvstr = ""; byte[] recvbytes = new byte[1024]; int bytes; bytes = c.receive(recvbytes, recvbytes.length, 0); recvstr += encoding.ascii.getstring(recvbytes, 0, bytes); console.writeline("client get message:{0}", recvstr); //close client c.close(); } catch (argumentexception e) { console.writeline("argumentnullexception:{0}",e); } catch (socketexception e) { console.writeline("socketexception:{0}",e); } console.writeline("press enter to exit"); console.readline();
来源:内容来自网络