Server:
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace socket { class Program { static void Main(string[] args) { int recv; // 定义一个空数组作为数据缓冲器,缓冲流入和流出的消息 byte[] data = new byte[1024]; // IPEndPoint ip地址和端口绑定,用来进行socket服务 // IPAddress.Any 设置可以接受任何网络接口的请求,也可以设置特殊的网络接口,如“192.168.1.6”,9050是端口号 IPEndPoint ipep = new IPEndPoint(IPAddress.Any,9050); // 创建Tcp套接字 Socket newsock = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); // 用Bind和Linsten将该套接字与ipEndPoint进行绑定 Console.WriteLine("Waiting for a client..."); // client用来接受客户端的接入连接尝试,Accept()返回一个新的socket对象 Socket client = newsock.Accept(); // 得到客户机的信息,并打印出来 IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}",clientep.Address, clientep.Port); string welcome = "Welcome to my test server"; // Encoding.ASCII用于字符串与字符数组间的转换 data = Encoding.ASCII.GetBytes(welcome); client.Send(data,data.Length,SocketFlags.None); while (true) { data = new byte[1024]; recv = client.Receive(data); if (recv == 0) { break; } Console.WriteLine(Encoding.ASCII.GetString(data, 0 ,recv)); client.Send(data, recv, SocketFlags.None); } Console.WriteLine("Disconnected from {0}",clientep.Address); client.Close(); newsock.Close(); } } }
client:
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace SimpleTcpSrvr { class Program { static void Main(string[] args) { byte[] data = new byte[1024]; string input, stringData; // 设置服务器ip进行连接, IPEndPoint ipep =new IPEndPoint(IPAddress.Parse("10.85.0.36"), 9050); Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); } catch (SocketException e) { Console.WriteLine("Unable to connect to server"); Console.WriteLine(e.ToString()); return; } int recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); while(true) { input = Console.ReadLine(); if (input == "exit") break; server.Send(Encoding.ASCII.GetBytes(input)); data = new byte[1024]; recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); }; Console.WriteLine("Disconnecting from server..."); server.Shutdown(SocketShutdown.Both); server.Close(); } } }