The program uses the TCP protocol. Of course, Shenma is the TCP protocol. You can use Baidu. To facilitate the use of the TCP protocol for C #,
Using System. Net. Sockets; uses the TcpListener class to simplify TCP server operations. Note that it is the server side. After all, we only need to listen on the server side.
We only need to define an object variable to perform server operations.
Of course, TcpListener has two parameter formats:
Public TcpListener (IPAddress localaddr, int port) the first parameter indicates the local IP address, and the second parameter indicates the listening port number.
After setting, start () is used to start listening for connection requests. If a connection request is received, start () queues the request and continues listening for whether there is another request, until the stop method is called.
Of course, the stop method is to disable TcpListener and stop listening.
Publi Socket AcceptSocket () is used in the program. This is a blocking method. When a customer connects, a socket instance is returned. In this way, the Send and Receive methods can be called to Send messages.
To facilitate data transmission, the program uses the NetworkStream class to access network data streams.
Of course, the premise is to create a new NetworkStream instance. Using this method, the Socket parameter in public NetworkStream (socket) is the socket used to send data, and the above AcceptSocket can be used to create a data stream.
StreamRead is used to receive data, and StreamWrite is used to send data.
Okay. Here is some code in the program to help you better understand it.
This is directly copied from the program, and some parameters may not be used.
Define parameters
private TcpListener tcpListener; private NetworkStream[] netWorkStream; private StreamReader[] streamReader; private StreamWriter[] streamWriter; private Socket[] socketForClient; private int CurPort; private IPAddress CurIp;
Start listening
private void btnStratServer_Click(object sender, EventArgs e) { serverThread = new Thread(new ThreadStart(Listen)); serverThread.Start(); // Listen(); }
Necessary parameter value assignment
CurIp = IPAddress. parse (txtIP. text); CurPort = Convert. toInt32 (txtPort. text); tcpListener = new TcpListener (CurIp, CurPort); // start to listen to tcpListener. start (); listInfo. items. add ("start server ");
Listeners
socketForClient[i] = tcpListener.AcceptSocket();
Create Data Flow
netWorkStream[i] = new NetworkStream(socketForClient[i]); streamReader[i] = new StreamReader(netWorkStream[i]); streamWriter[i] = new StreamWriter(netWorkStream[i]); recvThread = new Thread(new ParameterizedThreadStart(RecvAndSendData)); recvThread.Start(i);
Example of sending and receiving data
streamWriter[i].WriteLine("hahahahahah"); streamWriter[i].Flush();
string Pass = streamReader[i].ReadLine();
Now the process is basically implemented. If you have any questions, you can send them to source code research \ (^ o ^ )/~