晚上想寫點東西,想想把我剛來公司學的Sockt通訊寫上來吧。要寫的簡單易懂點,新人們可以借鑒下哦,用控制台寫。
先得說說Socket,與TCP/UDP啥關系,一直講什麼Socket通訊,TCP通訊,都被搞亂了,開始也搞不懂啥意思,引用網上大多數人講的概念吧“Socket接口是TCP/IP網絡的API,Socket接口定義了許多函數或例程,程序員可以用它們來開發TCP/IP網絡上的應用程序。要學Internet上的TCP/IP網絡編程,必須理解Socket接口。”我理解就是SOCKET是TCP、UDP的實現方式,用SOCKET編程可以實現TCP、UDP的通信。再通俗點,把Socket看成管子嘛,管子裡傳輸液體或是固體,就是不同的協議嘛。
好,下面切入主題看代碼,代碼不長,應該好懂。
服務器端:
static void Main(string[] args)
{
int recv;//用於表示客戶端發送的信息長度
byte[] data = new byte[1024];//用於緩存客戶端所發送的信息,通過socket傳遞的信息必須為字節數組
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//本機預使用的IP和端口
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);//綁定
newsock.Listen(10);//監聽
Console.WriteLine("waiting for a client");
Socket client = newsock.Accept();//當有可用的客戶端連接嘗試時執行,並返回一個新的socket,用於與客戶端之間的通信
IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("connect with client:" + clientip.Address + " at port:" + clientip.Port);
string welcome = "welcome here!";
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);//發送信息
try
{
while (true)
{//用死循環來不斷的從客戶端獲取信息
data = new byte[1024];
recv = client.Receive(data);
Console.WriteLine("recv=" + recv);
if (recv == 0)//當信息長度為0,說明客戶端連接斷開
break;
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
client.Send(data, recv, SocketFlags.None);//發送信息
}
}
catch
{
Console.WriteLine("Disconnected from" + clientip.Address);
}
client.Close();
newsock.Close();
}
客戶端:
static void Main(string[] args)
{
byte[] data = new byte[1024];
Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.Write("please input the server ip:");
string ipadd = Console.ReadLine();
Console.WriteLine();
Console.Write("please input the server port:");
int port = Convert.ToInt32(Console.ReadLine());
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);//服務器的IP和端口
try
{
//因為客戶端只是用來向特定的服務器發送信息,所以不需要綁定本機的IP和端口。不需要監聽。
newclient.Connect(ie);
}
catch (SocketException e)
{
Console.WriteLine("unable to connect to server");
Console.WriteLine(e.ToString());
return;
}
newclient.Send(Encoding.Default.GetBytes("watchdog"));
int recv = newclient.Receive(data);
string stringdata = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringdata);
while (true)
{
string input = Console.ReadLine();
if (input == "exit")
break;
newclient.Send(Encoding.ASCII.GetBytes(input));
data = new byte[1024];
recv = newclient.Receive(data);
stringdata = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringdata);
}
Console.WriteLine("disconnect from sercer");
newclient.Shutdown(SocketShutdown.Both);
newclient.Close();
}
客戶端運行圖
先運行服務端,再運行客戶端即可。這個程序麻雀雖小五髒俱全,還是很容易學習滴。延伸下去還可以做個簡易聊天室。