1. Service-side
New Project creation method for creating a console with C #
Startserversync () to implement a synchronization service with the client, however, this flaw is obvious and there are two points to wait
<summary>///Synchronous server///</summary> static void Startserversync () {Socket servesocket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);//parameter one means using IP 4, parameter two indicates the use of flow transmission, parameter three indicates the use of TCP protocol ipaddress ipaddress = Ipaddress.parse ("127.0.0.1");//Native IP address ipendpoint i
Pendpoint = new IPEndPoint (ipaddress, 8088); Servesocket.bind (ipendpoint);/bound port number Servesocket.listen (10);//Start listening port number, 10 represents a queue, this queue allows up to 10 clients to connect to queue, if set to 0 can let Unlimited client queues to connect let the server handle the Socket Clientsocket = servesocket.accept ();//Use Servesocket.accept () to connect the servers to a client, this method suspends the program straight
To receive a client, return the connected socket//Send a message to the client string msg = "Welcome! Hello";
byte[] data = Encoding.UTF8.GetBytes (msg);//convert string to bit clientsocket.send (data);
Accept a message from the client byte[] DataBuffer = new byte[1024]; int count = clientsocket.receive (databuffer);//clientsocKet. Receive (DataBuffer) accepts a byte of data stored in DataBuffer, the return value is the number of byte received, and this method pauses the program until it receives the data string msgreceive = Encoding.UTF8.Ge
Tstring (databuffer, 0, count);//Get databuffer[0] to Databuffer[count "byte conversion to String return Console.WriteLine (msgreceive);
Console.readkey (); Clientsocket.close ()//Close the connection to the client servesocket.close ()//Close the service-side Connection}
Next realizes the server and the client asynchronous connection, may realize the multiple Client connection service side, here we use the Socket.beginaccept (Asynccallback,object) method to let the servers begin to connect a client, The parameter AsyncCallback can be a method of our own definition, where we use our own acceptcallback (IAsyncResult) method, and the second parameter is to pass arguments to our method.
Define a global variable first
Static byte[] DataBuffer = new byte[1024];//used to store collected data
<summary>
///Server (asynchronous)
///</summary>
static void Startserverasync ()
{
Socket Servesocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);//Parameter one indicates the use of IP4, and parameter two indicates the use of stream transport, Parameter three indicates the use of
the TCP protocol ipaddress ipaddress = Ipaddress.parse ("127.0.0.1");//native IP address
ipendpoint ipendpoint = new IPEndPoint (IPAddress, 8088);
Servesocket.bind (ipendpoint);/bound port number
Servesocket.listen (10);//Start listening port number, 10 represents a queue, this queue allows up to 10 clients to be connected in line, If set to 0, you can have an unlimited number of clients queued to be connected to the server for processing
servesocket.beginaccept (acceptcallback, servesocket); Call function Acceptcallback () Start asynchronous connection Client
}
Servesocket.beginaccept (Acceptcallback, Servesocket); the second argument is actually passed to the Acceptcallback () method, which is equivalent to Acceptcallback ( Servesocket);
When we use Servesocket.beginaccept (Acceptcallback, Servesocket) The program is not paused and will continue to execute, except that we do not have the code to execute here. This is just beginning to receive a client, Does not accept a client.
We passed the server socket past to facilitate the connection with the client in the method
///<summary>///callback function for connection client///</summary>///<p Aram name= "ar" ></param> static void Acceptcallback (IAsyncResult ar) {Socket Servesoc Ket = ar.
AsyncState as Socket; Socket clientsocket = servesocket.endaccept (AR);//complete a client connection//send a message to the client string msg = "Welcome!"
Hello ";
byte[] data = Encoding.UTF8.GetBytes (msg);//convert string to bit clientsocket.send (data); Start listening for client data delivery//start receiving data, fourth parameter SocketFlags not needed here, so. None,receivecallback () is a custom method, which means that we call the method after we receive the data. The last parameter is the passing of the parameter in the ReceiveCallback () method, which is the object type clientsocket.beginreceive (DataBuffer, 0, 1024, socketflags.no
NE, ReceiveCallback, clientsocket); Servesocket.beginaccept (Acceptcallback, servesocket);//Continue processing next client connection}
Socket clientsocket = servesocket.endaccept (AR); This is the complete connection to a client socket. The last callback from the function implements multiple client connections. Similarly, We use Clientsocket.beginreceive (databuffer, 0, 1024, Socketflags.none, ReceiveCallback, Clientsocket); Start accepting data sent by clients,
Save to DataBuffer and call the ReceiveCallback () function, which is also a callback function, to implement multiple data sending per client. Use Clientscoket.endreceive (AR) to complete the delivery of the client data, at which time the data has been stored in the DataBuffer, if the client shuts down normally, this line of code will be an exception because the Clientsocket will be empty. If the client uses close
() method shuts down normally, the server receives a lot of empty data, which distinguishes the client from the way it is closed for different processing.
<summary>///Receive data callback function///</summary>///<param name= "AR" ></par am> static void ReceiveCallback (IAsyncResult ar) {Socket clientscoket = ar. AsyncState as socket;//casts a parameter to the Socket try {int count = clientscoket.endreceive (ar
)//completion of the client data delivery, return bits//client normal shutdown server will receive null data, but will not error, so here to handle the case of normal shutdown if (count==0)
{Clientscoket.close ();
Return
String msg = Encoding.UTF8.GetString (databuffer, 0, Count);
Console.WriteLine ("Customer said:" + msg); function callback so that you can receive multiple data clientscoket.beginreceive (databuffer, 0, 1024, Socketflags.none, ReceiveCallback, client
Scoket);
catch (Exception e) {Console.WriteLine (e); Handling an abnormal shutdown if (clientscoket==null) {clientscoket.close (); }
}
}
2. Client
In contrast, client code is fairly easy.
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Net.Sockets;
Using System.Net; Namespace Firstsocketclient {class Program {static void Main (string[] args) {Socket
Clientsocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Clientsocket.connect (New IPEndPoint (Ipaddress.parse ("127.0.0.1"), 8088);//Connect service//accept information byte[] Da
Ta =new byte[1024];
int count = clientsocket.receive (data);
String msg = Encoding.UTF8.GetString (data);
Console.WriteLine (msg);
Send information to server while (true) {string s = Console.ReadLine ();
if (S.equals ("//c")) {clientsocket.close ();
} clientsocket.send (Encoding.UTF8.GetBytes (s));
}
}
}
}