C# Socket實例(適合初學者)

注:很多代碼是從高手那裏弄來的,希望高手們莫怪,對你有用的幫忙頂下。
別忘記引進命名空間
using System.Net;
using System.Net.Sockets;

[b][size=x-large]Sever[/size][/b]

int port = 2000; //指定端口 (最後些在配置文件中)
String host = "127.0.0.1"; //指定IP
IPAddress ip = IPAddress.Parse(host);//把ip地址字符串轉換爲IPAddress類型的實例
IPEndPoint ipep = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint類的新實例

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+"atport:"+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();

[b][size=x-large]Client[/size][/b]

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;
}
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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章