客户端
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.IO; class Program { static void Main(string[] args) { SocketClient client = new SocketClient(); //发送消息 for (int i = 0; i < 10; i++) { client.SendMessage("Welcome To Qiku Edu, Happy new year, Good good study ,day day up!!!"); } while (true) { string msg = Console.ReadLine(); client.SendMessage(msg); } } } public class SocketClient { string ip = "192.168.11.3"; int port = 8500; NetworkStream stream; byte[] buffer; int BuffseSize = 8192; public SocketClient() { TcpClient client = new TcpClient(); client.Connect(ip, port); Console.WriteLine("连接服务器 -> " + client.Client.RemoteEndPoint); stream = client.GetStream(); buffer = new byte[8192]; stream.BeginRead(buffer,0,buffer.Length, ReadAsync,null); } void ReadAsync(IAsyncResult result) { try { int readCount = stream.EndRead(result); if (readCount == 0) throw new Exception("读取到0字节"); string msg = Encoding.UTF8.GetString(buffer, 0, readCount); Console.WriteLine("接收到消息 -> " + msg); lock (stream) //再次开启读取 { Array.Clear(buffer, 0, buffer.Length); stream.BeginRead(buffer, 0, BuffseSize, ReadAsync, null); } } catch (Exception e) { Console.WriteLine(e.Message); } } //发送消息到服务器 public void SendMessage(string msg) { //把内容转为byte[] byte[] temp = Encoding.UTF8.GetBytes(msg); //把长度转为byte int length = temp.Length; byte[] head = BitConverter.GetBytes(length); //拼接最后的byte数组 MemoryStream mem = new MemoryStream(); mem.Write(head, 0, head.Length); mem.Write(temp, 0, temp.Length); //发送最终内容 byte[] result = mem.ToArray(); stream.Write(result, 0, result.Length); Console.WriteLine("发送消息 -> " + msg); } }
服务器
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; class Program { static Dictionary<string, RemoteClient> dic = new Dictionary<string, RemoteClient>(); static void Main(string[] args) { IPAddress address = IPAddress.Parse("192.168.11.3"); int port = 8500; TcpListener listener = new TcpListener(address, port); listener.Start(); Console.WriteLine("开始侦听"); while (true) { TcpClient client = listener.AcceptTcpClient(); //接收到客户端后,交给RemoteCient去处理 RemoteClient remote = new RemoteClient(client); dic.Add(client.Client.RemoteEndPoint.ToString(), remote); } } public static void Broad(TcpClient client, string msg) { foreach (KeyValuePair<string, RemoteClient> item in dic) { string message = client.Client.RemoteEndPoint.ToString() + ":发送了:" + msg; item.Value.SendMessage(message); } } } //class Program //{ // static TcpListener listener; // static void Main(string[] args) // { // IPAddress address = IPAddress.Parse("192.168.99.156"); // int port = 8500; // listener = new TcpListener(address, port); // listener.Start(); // Console.WriteLine("开始侦听"); // listener.BeginAcceptTcpClient(OnConnet, null); // Console.ReadLine(); // } // static void OnConnet(IAsyncResult result) // { // TcpClient client = listener.EndAcceptTcpClient(result); // Console.WriteLine("连接成功"); // //接收到客户端后,交给RemoteCient去处理 // RemoteClient remote = new RemoteClient(client); // listener.BeginAcceptTcpClient(OnConnet, null); // } //}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; namespace ConsoleServer.Properties { class FirstServer { const int BufferSize = 8192; string ip = "192.168.11.3"; int port = 8500; public FirstServer() { IPAddress address = IPAddress.Parse(ip); TcpListener listener = new TcpListener(address, port); listener.Start(); Console.WriteLine("服务器开始侦听"); while (true) { //等待客户端连接 TcpClient client = listener.AcceptTcpClient(); Console.WriteLine(client.Client.RemoteEndPoint + " -> 连接成功"); //获取网络流 NetworkStream stream = client.GetStream(); while (true) { byte[] buffer = new byte[BufferSize]; int readCount = stream.Read(buffer, 0, BufferSize); string msg = Encoding.UTF8.GetString(buffer, 0, readCount); Console.WriteLine("接收到消息 -> " + msg); } } Console.WriteLine("输入任意键退出"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Net; using System.Text; using System.Threading.Tasks; using System.IO; class RemoteClient { public const int BuffseSize = 8192; TcpClient tcpClient; NetworkStream stream; byte[] buffer; public RemoteClient(TcpClient client) { this.tcpClient = client; Console.WriteLine(client.Client.RemoteEndPoint + " -> 连接成功"); stream = client.GetStream(); buffer = new byte[BuffseSize]; //开启异步读取消息 stream.BeginRead(buffer, 0, BuffseSize, ReadAsync, null); } void ReadAsync(IAsyncResult result) { try { int readCount = stream.EndRead(result); if (readCount == 0) throw new Exception("读取到0字节"); //抛出到逻辑层 OnReceive(buffer, readCount); lock (stream) //再次开启读取 { Array.Clear(buffer, 0, buffer.Length); stream.BeginRead(buffer, 0, BuffseSize, ReadAsync, null); } } catch (Exception e) { Console.WriteLine(e.Message); } } MemoryStream mem = new MemoryStream(); //解密消息体 void OnReceive(byte[] bytes, int count) { mem.Seek(0,SeekOrigin.End); mem.Write(bytes, 0, count); mem.Seek(0,SeekOrigin.Begin); while (RemainingBytes() > 4) { byte[] head = new byte[4]; mem.Read(head, 0, 4); int length = BitConverter.ToInt32(head, 0); if (RemainingBytes() >= length) { byte[] content = new byte[length]; mem.Read(content, 0, length); string msg = Encoding.UTF8.GetString(content); Console.WriteLine(msg); } else { mem.Position = mem.Position - 4; break; } } //把剩余的写到mem的开头 byte[] remain = new byte[mem.Length - mem.Position]; mem.Read(remain, 0, remain.Length); mem.SetLength(0); mem.Write(remain, 0, remain.Length); } long RemainingBytes() { return mem.Length - mem.Position; } //发送给客户端消息 public void SendMessage(string msg) { byte[] temp = Encoding.UTF8.GetBytes(msg); stream.Write(temp, 0, temp.Length); Console.WriteLine(msg); } }