|
How to use socket in client application? //first, new a socket object. //socket class is included in system.net.sockets. //this socket can be used to tcp/ip application: Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //this socket can be used to udp application: Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//second, connect to sever public void Connect(EndPoint remoteEP) //the endpoint is composed of IP and port. //IP can be get through the Parse method of IPAddress class: IPAddress myIP = IPAddress.Parse("192.168.1.2"); //you can also get ip from a domain name through the method below: IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com"); IPAddress ipAddress = ipHostInfo.AddressList[0]; // knowing the ip and port, u can get the EndPoint: IPEndPoint ipe = new IPEndPoint(ipAddress,11000); // having the EndPoint, connect to server: try { s.Connect(ipe); } catch(ArgumentNullException ae) { Console.WriteLine("ArgumentNullException : {0}", ae.ToString()); } catch(SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch(Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); }
// if you want to send data to server, you can use "send" method. public int Send(byte[], int, SocketFlags); // before you send a string to server, you must convert it to bytes. byte[] bytesSendStr=new byte[1024]; bytesSendStr=Encoding.ASCII.GetBytes(sendStr); // then send bytes to server: socket.Send(bytesSendStr,bytesSendStr.Length,0);
// you can use "recieve" method to recieve data from server. public int Receive(byte[],int,SocketFlags); // you probably need to convert bytes to string. byte[] recvBytes=new byte[1024]; int bytes=0; while(true) { bytes=socket.Receive(recvBytes,recvBytes.Length,0); if(bytes<=0) break; recvStr+=Encoding.ASCII.GetString(recvBytes,0,bytes); }
//when you needn't socket any more, shutdown and close it. public void Shutdown( SocketShutdown how ); public void Close();
How to use socket in server application? //same to client app, u need new a socket also. Scoket listener(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //u can get local IP as below: IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddr = ipHostInfo.AddressList(0); // then, bind the socket with a local endpoint. public void Bind( EndPoint localEP ); // listen to connect request. public void Listen( int backlog ); for example: listener.Listen(10) // if hear a connect request, accept it and new a socket more to treat later request. for example: Scoket handler = listener.Accept(); // when this session is over, shutdown and close handler. handler.Shutdown(SocketShutdown.Both); handler.Close(); //when server app exit, shutdown and close listener.
Those codesare not runable, which only expressed how to use socket.
|