
無連接的套接字系統調用時序
3.開始動手敲~~代碼(簡單的代碼)
首先我們來寫個面向連接的
TCPServer
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace tcpserver
{
/// <summary>
/// Class1 的摘要說明。
/// </summary>
class server
{
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此處添加代碼以啟動應用程序
//
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);//發送信息
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);
}
Console.WriteLine("Disconnected from"+clientip.Address);
clIEnt.Close();
newsock.Close();
}
}
}