Socket 通讯协议主要有两种,一种是Tcp,另一种是Udp,显示情况中一般使用的都是Tcp,因为Udp 可能会丢数据

客户端代码:

   //创建发送数据的Socket,包括ip类型、数据类型、协议类型
       

Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //设置发送数据的地址
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345);
            //创建读取文件的流
            FileStream fileStream = new FileStream(Server.MapPath("123.txt"), FileMode.OpenOrCreate, FileAccess.Read);            //文件大小
            Byte[] fsSize = new Byte[fileStream.Length - 1];
            //读取文件的二进制流
            BinaryReader reader = new BinaryReader(fileStream);
            //读取数据
            reader.Read(fsSize, 0, (int)fileStream.Length - 1);
            //链接目的地
            sendSocket.Connect(endPoint);
            //发送数据
            sendSocket.Send(fsSize);
            //关闭文件流
            fileStream.Close();
            //关闭发送数据的Socket
            sendSocket.Shutdown(SocketShutdown.Send);
            sendSocket.Close();

客户端采用TcpClient 实现:

 

int port=12345;
    string server= ""127.0.0.1;
   TcpClient client=new TcpClient(server,port);  //创建TcpClient并设置发送地址
    string sendMessage = "待发送的数据";
    Byte[] data = new Byte[2048];
     data= System.Text.Encoding.ASCII.GetBytes(message);
    NetworkStream stream =client.GetStream();  //为写入和读取数据,获取客户端数据流
    stream.Write(data,0,data.length);  
 
    string receiveMessage = string.Empty;
    Byte[] receiveByte=new Byte[2048];
    while(string.ISNullOrEmpty(receiveMessage))
    {
    stream.Read(receiveByte,0,receiveByte.Length);  //读取数据
    receiveMessage = System.Text.Encoding.ASCII.GetString(receiveByte);
    }
    stream.Close();
    client.Close();