首页 > 代码库 > Socket的简单例子

Socket的简单例子

服务器端

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net;using System.Net.Sockets;//Socket相关的类namespace ChatServer{class Program{static void Main(string[] args){//创建服务器上的监听Socket对象,用来监听客户端的连接请求Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//公开一个IP地址和端口号(终结点EndPoint)IPEndPoint ep = new IPEndPoint(IPAddress.Any, 18888);//将监听Socket对象绑定到终结点server.Bind(ep); //开始监听,100指排队的队列长度server.Listen(100);Console.WriteLine("服务器已经启动了......");//如果有客户端的连接请求,则接收该连接,自动启动一个数据收发的Socekt对象Socket socket = server.Accept();//接收数据byte[] buffer = new byte[1024];int length = socket.Receive(buffer);Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer, 0, length));string info = string.Format("At {0} Server Recive {1} byte info",DateTime.Now.ToString(),length);socket.Send(System.Text.Encoding.UTF8.GetBytes(info));}}}

 

客户端

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net;using System.Net.Sockets;namespace ChatClient{class Program{static void Main(string[] args){Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//Connect连接 的终结点是服务器公开的终结点client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),18888));Console.WriteLine("连接成功了");string info = "hello,I am mwh";//发送数据client.Send(System.Text.Encoding.UTF8.GetBytes(info));byte[] buffer = new byte[1024];int length = client.Receive(buffer);Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer, 0, length));}}}