C# tcp
用的c#自带的对socket进一步封装的函数,下面是代码:
服务端:
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace tcpServer { class Program { //服务器端 static void Main(string[] args) { TcpListener listener = new TcpListener(IPAddress.Parse("192.168.1.104"), 2222); listener.Start();//开始监听 TcpClient client = listener.AcceptTcpClient();//获取客户端的socket NetworkStream stream = client.GetStream();//获取流 byte[] data = new byte[1024]; while (true) { int length = stream.Read(data, 0, 1024); string message = Encoding.UTF8.GetString(data, 0, length); Console.WriteLine("消息:" + message); } /* //关闭程序不要忘了做下面操作(指有退出事件的时候) stream.Close(); client.Close(); listener.Stop(); */ } } }
客户端:
using System; using System.ComponentModel; using System.Net; using System.Net.Sockets; using System.Text; namespace tcpClient { //客户端 class Program { static void Main(string[] args) { //当我们创建tcpclient对象,服务器的ip和端口号 TcpClient client = new TcpClient("192.168.1.104", 2222); NetworkStream stream = client.GetStream();//通过网络流进行数据的交换 //read用来读取数据,write用来发送数据 while (true) { string message = Console.ReadLine(); byte[] data = Encoding.UTF8.GetBytes(message); stream.Write(data, 0, data.Length); } /* //实际使用过程中在程序关闭的时候不要忘了关闭连接 stream.Close(); client.Close(); */ } } }
结果:
socket类实现:
服务端代码:
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; public class SocketServer { private string _ip = string.Empty; private int _port = 0; private Socket _socket = null; private byte[] buffer = new byte[1024 * 1024 * 2]; /// <summary> /// 构造函数 /// </summary> /// <param name="ip">监听的IP</param> /// <param name="port">监听的端口</param> public SocketServer(string ip, int port) { _ip = ip; _port = port; } public SocketServer(int port) { _ip = "0.0.0.0"; _port = port; } public void StartListen() { try { //1.0 实例化套接字(IP4寻找协议,流式协议,TCP协议) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2.0 创建IP对象 IPAddress address = IPAddress.Parse(_ip); //3.0 创建网络端口,包括ip和端口 IPEndPoint endPoint = new IPEndPoint(address, _port); //4.0 绑定套接字 _socket.Bind(endPoint); //5.0 设置最大连接数 _socket.Listen(int.MaxValue); Console.WriteLine("监听{0}消息成功", _socket.LocalEndPoint.ToString()); //6.0 开始监听 Thread thread = new Thread(ListenClientConnect); thread.Start(); } catch (Exception ex) { throw; } } /// <summary> /// 监听客户端连接 /// </summary> private void ListenClientConnect() { try { //while (true) //{ // //Socket创建的新连接 // Socket clientSocket = _socket.Accept(); // clientSocket.Send(Encoding.UTF8.GetBytes("服务端发送消息:")); // Thread thread = new Thread(ReceiveMessage); // thread.Start(clientSocket); //} //Socket创建的新连接 Socket clientSocket = _socket.Accept(); clientSocket.Send(Encoding.UTF8.GetBytes("服务端发送消息:")); Thread thread = new Thread(ReceiveMessage); thread.Start(clientSocket); } catch (Exception) { throw; } } /// <summary> /// 接收客户端消息 /// </summary> /// <param name="socket">来自客户端的socket</param> private void ReceiveMessage(object socket) { Socket clientSocket = (Socket)socket; while (true) { try { //获取从客户端发来的数据 int length = clientSocket.Receive(buffer); Console.WriteLine("接收客户端{0},消息{1}", clientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length)); //SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP); clientSocket.SendTo(Encoding.UTF8.GetBytes("我收到了"), clientSocket.RemoteEndPoint); } catch (Exception ex) { Console.WriteLine(ex.Message); clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); break; } } } }
客户端代码:
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; public class SocketClient { private string _ip = string.Empty; private int _port = 0; private Socket _socket = null; private byte[] buffer = new byte[1024 * 1024 * 2]; /// <summary> /// 构造函数 /// </summary> /// <param name="ip">连接服务器的IP</param> /// <param name="port">连接服务器的端口</param> public SocketClient(string ip, int port) { _ip = ip; _port = port; } public SocketClient(int port) { _ip = "127.0.0.1"; _port = port; } /// <summary> /// 开启服务,连接服务端 /// </summary> public void StartClient() { try { //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2.0 创建IP对象 IPAddress address = IPAddress.Parse(_ip); //3.0 创建网络端口包括ip和端口 IPEndPoint endPoint = new IPEndPoint(address, _port); //4.0 建立连接 _socket.Connect(endPoint); Console.WriteLine("连接服务器成功"); //5.0 接收数据 //while (true) //{ // int length = _socket.Receive(buffer); // Console.WriteLine("接收服务器{0},消息:{1}", _socket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length)); //} Thread thread = new Thread(Receive); thread.Start(_socket); //6.0 像服务器发送消息 while (true) { string strMsg = Console.ReadLine(); _socket.Send(Encoding.UTF8.GetBytes(strMsg)); } //for (int i = 0; i < 10; i++) //{ // Thread.Sleep(2000); // string sendMessage = string.Format("客户端发送的消息,当前时间{0}", DateTime.Now.ToString()); // _socket.Send(Encoding.UTF8.GetBytes(sendMessage)); // Console.WriteLine("像服务发送的消息:{0}", sendMessage); //} } catch (Exception ex) { _socket.Shutdown(SocketShutdown.Both); _socket.Close(); Console.WriteLine(ex.Message); } Console.WriteLine("发送消息结束"); Console.ReadKey(); } /// <summary> /// 接收服务器返回的消息 /// </summary> /// <param name="socket"></param> private void Receive(object socket) { while (true) { Socket tempSocket = (Socket)socket; int length = tempSocket.Receive(buffer); Console.WriteLine("接收服务器{0},消息:{1}", tempSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length)); } } }