關於C#socket通信,分為同步和異步通信,本文簡單介紹一下同步通信。
通信兩端分別為客戶端(Client)和服務器(Server):
(1)Cient:
1:建立一個Socket對像;
2:用socket對像的Connect()方法以上面建立的EndPoint對像做為參數,向服務器發出連接請求;
3:如果連接成功,就用socket對像的Send()方法向服務器發送信息;
4:用socket對像的Receive()方法接受服務器發來的信息 ;
5:通信結束后一定記得關閉socket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace Client
{
class Program
{
static Socket ClientSocket;
static void Main(string[] args)
{
String IP = "127.0.0.1";
int port =8885 ;
IPAddress ip = IPAddress.Parse(IP); //將IP地址字符串轉換成IPAddress實例
ClientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//使用指定的地址簇協議、套接字類型和通信協議
IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口號初始化IPEndPoint實例
ClientSocket.Connect(endPoint); //與遠程主機建立連接
Console.WriteLine("開始發送消息");
byte[] message = Encoding.ASCII.GetBytes("Connect the Server"); //通信時實際發送的是字節數組,所以要將發送消息轉換字節
ClientSocket.Send(message);
Console.WriteLine("發送消息為:" + Encoding.ASCII.GetString(message));
byte[] receive = new byte[1024];
int length = ClientSocket.Receive(receive); // length 接收字節數組長度
Console.WriteLine("接收消息為:" + Encoding.ASCII.GetString(receive));
ClientSocket.Close(); //關閉連接
}
}
}
客戶端返回結果:


(2)Server:
1:建立一個Socket對像;
2:用socket對像的Bind()方法綁定EndPoint;
3:用socket對像的Listen()方法開始監聽;
4:接受到客戶端的連接,用socket對像的Accept()方法創建新的socket對像用於和請求的客戶端進行通信;
5:用新的socket對象接收(Receive)和發送(Send)消息。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace Server
{
class Program
{
static Socket ReceiveSocket;
static void Main(string[] args)
{
int port = 8885;
IPAddress ip = IPAddress.Any; // 偵聽所有網絡客戶接口的客活動
ReceiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇協議、套接字類型和通信協議
ReceiveSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true); //有關套接字設置
IPEndPoint endPoint = new IPEndPoint(ip,port);
ReceiveSocket.Bind(new IPEndPoint(ip, port)); //綁定IP地址和端口號
ReceiveSocket.Listen(10); //設定最多有10個排隊連接請求
Console.WriteLine("建立連接");
Socket socket = ReceiveSocket.Accept();
byte[] receive = new byte[1024];
socket.Receive(receive);
Console.WriteLine("接收到消息:" + Encoding.ASCII.GetString(receive));
byte[] send = Encoding.ASCII.GetBytes("Success receive the message,send the back the message");
socket.Send(send);
Console.WriteLine("發送消息為:"+Encoding.ASCII.GetString(send));
}
}
}
服務器返回結果:
