天天看点

C#Socket通信

服务器基本流程:

  1. 创建Socket实例
  2. 绑定ip和端口号
  3. 设置最大连接数
  4. 监听来自客户端的连接请求
  5. 接收来自客户端的数据
  6. 向客户端发送数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Socket服务端
{
    class Program
    {
        public static void Main()
        {
            #region socket服务端通信基本流程
            //创建socket
            Socket tcpSocket = new Socket(SocketType.Stream,ProtocolType.Tcp);
            //绑定ip和端口
            EndPoint point = new IPEndPoint(IPAddress.Any,1024);
            tcpSocket.Bind(point);
            //设置最大连接数
            tcpSocket.Listen(100);
            Console.WriteLine("监听客户端连接");
            //等待客户端连接
           Socket serverSocket= tcpSocket.Accept();
            //发送数据
            byte[] data = Encoding.UTF8.GetBytes("服务器:连接成功!");
            serverSocket.Send(data);
            //接收来自客户端的数据
            byte[] data2 = new byte[1024];
            //接收到的数据将暂时放入data2中
           int length= serverSocket.Receive(data2);
            //输出数据
            Console.WriteLine(Encoding.UTF8.GetString( data2, 0, length));
            
            #endregion


            Console.ReadKey();
        }
    }
}

           

注意事项:服务器对数据的收发都是通过,Accept方法完成连接后返回的socket对象来做的

客户端基本流程:

  1. 创建Socket实例
  2. 和服务器建立连接
  3. 接收来自服务器的数据
  4. 向服务器发送数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Socket客户端
{
    class Program
    {
        static void Main(string[] args)
        {
            #region socket客户端基本逻辑
            //创建客户端实例
            Socket clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
            EndPoint point2 = new IPEndPoint(IPAddress.Parse("192.168.0.106"), 1024);
            //连接服务器
            clientSocket.Connect(point2);
            //向服务器发送数据
            clientSocket.Send(Encoding.UTF8.GetBytes("客户端:呼叫总部,请求支援!"));
            //接收来自服务器的数据
            byte[] data2 = new byte[1024];
           int len= clientSocket.Receive(data2);
            //输出数据
            Console.WriteLine(Encoding.UTF8.GetString(data2, 0, len));
            //关闭连接
            clientSocket.Close();
            #endregion
            Console.ReadKey();
        }
    }
}

           

输出结果:

C#Socket通信
C#Socket通信