1、鉴于实时交互的网络需求,基于TCP/IP协议的网络功能,使用.Net提供的Socket功能,制作一个聊天程序。 2、Server端。 2.1首先创建一个Socket,并将它绑定到服务器的地址和端口上 2.2然后开始监听客户端的连接。 2.3在接受到客户端的连接后,将客户端发来的一个数据存储到一个Byte数组中,并返回给客户端。 using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; namespace _2018._1._16自己写的Socket服务端 { class Program { static void Main(string[] args) { string ip=“127.0.0.1”; int port=8000; try{ //获得终端。 IPEndPoint ipe=new IPEndPoint(IPAddress.parse(ip),port); Socket serverSocket=new Socket(AddressFamily.InterNetWork,SocketType.Stream,ProtocolType.Tcp); //绑定端口号。 serverSocket.Bind(ipe); //最大允许监听1000个 serverSocket.Listen(1000); //开始监听客户端,程序会在这里止住。 Socket clientSocket=serverSocket.Acccept(); //接收客户端的消息 byte []bs=new byte[1024]; int n = clientSocket.Receive(bs); Console.WriteLine(UTF8Encoding.UTF8.GetString(bs)); //向客户端发送消息。 string msg=“Helllo,客户端。”; byte[] b=UTF8Encoding.UTF8.GetByte(msg); clientSocket.Send(msg); clientSocket.Close(); }catch(Exception ex) { Console.WriteLine(ex.Message); } } } }
3、Client端。 3.1很多与Server端相似, 3.2不同地方:接受客户端连接的步骤变成了连接服务器的请求。 using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; namespace _2018._1._16自己写的客户端 { class Program { static void Main(string[] args) { string ip = “127.0.0.1”; int port = 8000; try { IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port); Socket clientSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(ipe); //向服务器发送消息。 String msg = “Hello,服务器”; byte[] bs = UTF8Encoding.UTF8.GetBytes(msg); clientSocket.Send(bs); //接收服务器返回的消息。 byte[] b= new byte[256]; clientSocket.Receive(bs); Console.WriteLine(UTF8Encoding.UTF8.GetString(b)); clientSocket.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }