直接上代碼,看完你就懂了。
public class Socketer { /// <summary> /// Server /// </summary> /// <param name="serverport">ServerPort</param> public Socketer(int serverport) { Initilize_Bind(serverport); Socket_host.Listen(1); Socket_host.BeginAccept(ar => { //這裡要注意我這裡上面只監聽了一個串連,而下面這句也只是簡答地吧原來的Socket給覆蓋了,如果你要改成多用戶端的話需要增加一個列表, // 並且對列表中的Socket對象分別進行相應的操作 Socket_host = Socket_host.EndAccept(ar); Recive(); }, null); } //IPAddress _HostIP; //public IPAddress HostIP { get { return _HostIP; } } /// <summary> /// Client /// </summary> /// <param name="clientport">ClientPort</param> /// <param name="serverport">ServerPort</param> public Socketer(int clientport, int serverport) { Initilize_Bind(clientport); Socket_host.BeginConnect(new IPEndPoint(IPAddress.Loopback, serverport), ar => { Socket_host.EndConnect(ar); Recive(); }, null); } private void Initilize_Bind(int hostport) { Socket_host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //_HostIP = ; Socket_host.Bind(new IPEndPoint(IPAddress.Any, hostport)); } public Socket Socket_host; //public List<Socket> Clients = new List<Socket>(); private byte[] Buffer_Recive = new byte[256]; private virtual void Recive() { if (Socket_host.Connected) { Array.Clear(Buffer_Recive, 0, Buffer_Recive.Length); Socket_host.BeginReceive(Buffer_Recive, 0, Buffer_Recive.Length, SocketFlags.None, ar => { int getsize= Socket_host.EndReceive(ar); if (GetMsg != null) { //GetMsg.Invoke(Encoding.UTF8.GetString(Buffer_Recive, 0, getsize)); //GetMsg.Method.Invoke(null, new object[]{ Encoding.UTF8.GetString(Buffer_Recive, 0, getsize)}); GetMsg(Encoding.UTF8.GetString(Buffer_Recive, 0, getsize)); //GetMsg.BeginInvoke(,null,null); } Recive(); }, null); } } public event GetResult GetMsg; public virtual void Send(string msg) { if (Socket_host.Connected) { byte[] sendbuffer = Encoding.UTF8.GetBytes(msg); Socket_host.BeginSend(sendbuffer, 0, sendbuffer.Length, SocketFlags.None, ar => { Socket_host.EndSend(ar); }, null); } } } public delegate void GetResult(string msg);//小菜
另說一下,不知道為什麼,寫文章時,代碼塊 刪除不掉,煩死人了
伺服器端和用戶端使用同一段代碼建立,是不是很簡單,很easy?
Socketer Server = new Socketer(9999);
Socketer Client = new Socketer(9998, 9999);
Server.GetMsg += new GetResult(Server_GetMsg);
Client.GetMsg += new GetResult(Client_GetMsg);
然後你就send吧...都不需要Recive了...
哎,編輯的時候還不能局部選中文字,這編輯器太爛了....估計就只有速度還可以這個優勢了...