C# Socket 例子(控制台程序)
服务器代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; namespace TCPListener { class Program { static void Main(string[] args) { const int BufferSize = 1024; Console.WriteLine("Sever is running...."); IPAddress IP = new IPAddress(new byte[] { 127, 0,0,1 }); TcpListener lister = new TcpListener(IP,8500); lister.Start(); Console.WriteLine("Start Listering...."); TcpClient remoteClient = lister.AcceptTcpClient(); Console.WriteLine("Client Connected!{0} <-- {1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint); NetworkStream streamToClient = remoteClient.GetStream(); try { while (true) { byte[] buffer = new byte[BufferSize]; int bytesRead = streamToClient.Read(buffer, 0, BufferSize); Console.WriteLine("Reading data {0} bytes....", bytesRead); // 获得请求的字符串 string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); Console.WriteLine("Received: {0}", msg); //将字符串转换为大写 msg = msg.ToUpper(); buffer = Encoding.Unicode.GetBytes(msg); lock (streamToClient) { streamToClient.Write(buffer, 0, buffer.Length); } Console.WriteLine("Sent: {0}", msg); } } catch(Exception e) { remoteClient.Close(); } //} Console.WriteLine("\n\n输入\"Q\"键退出。"); streamToClient.Dispose(); remoteClient.Close(); ConsoleKey Key; do { Key = Console.ReadKey(true).Key; } while (Key != ConsoleKey.Q); } } }
客户端代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace TCPconnect { class Program { static void Main(string[] args) { string msg; const int BufferSize = 1024; IPAddress SeverIP = IPAddress.Parse("127.0.0.1"); Console.WriteLine("TCPClient is running"); TcpClient Client; //for (int i = 0; i <= 2; i++) //{ try { Client = new TcpClient(); Client.Connect(SeverIP, 8500); } catch (Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine("Sever Connected! {0}-->{1}", Client.Client.LocalEndPoint, Client.Client.RemoteEndPoint); //} Console.WriteLine("请输入发送的内容"); NetworkStream StreamToSever = Client.GetStream(); ConsoleKey key; Console.WriteLine("Menu: S - Send, X - Exit"); do{ key = Console.ReadKey(true).Key; if (key == ConsoleKey.S) { msg = Console.ReadLine(); byte[] buffer = Encoding.Unicode.GetBytes(msg);//获取缓存 lock (StreamToSever) { StreamToSever.Write(buffer, 0, buffer.Length); } Console.WriteLine("Sent:{0}", msg); int bytesRead; buffer = new byte[BufferSize]; lock (StreamToSever) { bytesRead = StreamToSever.Read(buffer, 0, BufferSize); } msg = Encoding.Unicode.GetString(buffer, 0,bytesRead); Console.WriteLine("Received: {0}", msg); } } while (key != ConsoleKey.X); Console.WriteLine("\n\n输入\"Q\"键退出。"); ConsoleKey Key; do { Key = Console.ReadKey(true).Key; } while (Key != ConsoleKey.Q); } } }