Home>

Clients want to connect to the server:First they need to know the server's IP address. And there are many applications in the server,Each application corresponds to a port number

Therefore, if the client wants to communicate with an application in the server, it must know the IP address of the server where the application is located, and the port number corresponding to the application.

tcp protocol:Safe and stable,Data loss generally does not occur,But it is inefficient.Data generated using tcp generally passes through 3 handshake (all inefficient,Baidu's three-way handshake)

udp protocol:Fast and efficient, but unstable,Prone to data loss (without a three-way handshake,Whether the server is available or not,The information is all sent to the server,All efficiencyBut when the server is busy, there is no way to process your data,Easy to cause data loss,Unstable)

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.net.sockets;
using system.net;
using system.threading;
namespace socket communication
{
 public partial class form1:form
 {
 public form1 ()
 {
 initializecomponent ();
 this.txtport.text="5000";
 this.txtip.text="192.168.137.1";
 }
 private void btnstart_click (object sender, eventargs e)
 {
 //When the click starts listening,Create a socket on the server responsible for listening to the IP address and port number
 socket socketwatch=new socket (addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
 //any:Provide an ip address indicating that the server should listen for client activity on all network interfaces.
This field is read-only.
 ipaddress ip=ipaddress.any;
 //Create a port number object;
Set the value of the txtport.text control to the port number of the server
 ipendpoint point=new ipendpoint (ip, convert.toint32 (txtport.text));
 //monitor
 socketwatch.bind (point);
 showmsg ("Successful listening");
 socketwatch.listen (10);//The maximum length of the connection queue;that is, a maximum of several clients can be connected in a time point,Queuing over length
 //wait for client connection;
accept () This method can accept client connections,And create a socket responsible for communication for the new connection
 thread th=new thread (listen);//The method to be executed by the thread, if there are parameters,Parameter must be of type object
 control.checkforillegalcrossthreadcalls=false;//Because .net does not allow cross-thread access,So cancel the cross-thread check here.
.net does not check for cross-thread access,All will not report:"Access to the control" txtlog "from the thread" error,Thus achieving cross-thread access
 th.isbackground=true;//Set th as a background thread.
 //start (object parameter);parameter:an object,Contains the data to be used by the method executed by the thread,That is, the thread executes the listen method, and the parameters of the listen
 th.start (socketwatch);//The parameters in this bracket are actually the parameters of the listen () method.
Because thread th=new thread (listen), you can only write the method name (function name) in brackets, but the listen () method has parameters.
So you need to add its parameters using start () method
 }
 ///<summary>
 ///wait for the client to connect,If a client connection is monitored, a socket is created to communicate with
 ///</summary>
 ///<param name="o"></param>
 void listen (object o) //Why not pass a socket type parameter directly here?The reason is:if the method executed by the thread has parameters,Parameter must be of type object
 {
 socket socketwatch=o as socket;
 while (true) //Why is there a while loop here?Because when a person connects and creates a socket to communicate with, the program will be executed downwards.
You will not come back to create a socket responsible for communication for the second person's connection. (Everyone (each client) should create a socket to communicate with) So it should be written in a loop.
 {
 //wait for client connection;
accept () This method can accept client connections,And create a socket responsible for communication for the new connection
 socket socketsend=socketwatch.accept ();
 dic.add (socketsend.remoteendpoint.tostring (), socketsend);//(Find the socket responsible for communication according to the client's IP address and port number, and each client corresponds to a socket responsible for communication). key,The socket responsible for communication is populated as a value into the dic key-value pair.
 //We can get the IP address and port number of the remote client through a remoteteenpoint property of the socketsend object responsible for communication
 showmsg (socketsend.remoteendpoint.tostring () + ":" + "Connection succeeded");//Effect:192.168.1.32:Connection succeeded
 combobox1.items.add (socketsend.remoteendpoint.tostring ());//Add each client connected to the combbox control.
 //After the client is successfully connected,The server should receive messages from the client.
 thread getdata=new thread (getdata);
 getdata.isbackground=true;
 getdata.start (socketsend);
 }
 }
 dictionary<string, socket>dic=new dictionary<string, socket>();
 ///<summary>
 ///keep receiving messages from the client
 ///</summary>
 ///<param name="o"></param>
 void getdata (object o)
 {
 while (true)
 {
 socket socketsend=o as socket;
 //Put the data sent by the client into a byte array first
 byte [] buffer=new byte [1024 * 1024 * 2];//Create a byte array,The length of the byte array is 2m
 //The actual number of valid bytes received;
 (Use the receive method to receive data from the client.
Then save the data to the buffer byte array,(Returns the length of a received data)
 int r=socketsend.receive (buffer);
 if (r == 0) //If the number of valid bytes received is 0, the client is closed.
At this point, it is out of the loop.
 {
 //Only the client sends a message to the user,It is impossible to send zero-length bytes.
Even when sending empty messages,Empty messages also have a length.
All received valid byte length is 0, which means the client is closed
 break;
 }
 //Decode the data in the buffer byte array according to utf8 encoding and decode it into a string type that we can understand. Because the actual length of the data stored in the buffer array is r, it starts from the byte with index 0 decoding,Decode a total of r bytes in length.
 string str=encoding.utf8.getstring (buffer, 0, r);
 showmsg (socketsend.remoteendpoint.tostring () + ":" + str);
 }
 }
 private void showmsg (string str)
 {
 txtlog.appendtext (str + "\ r \ n");//Add the string str to the text box txtlog.
 }
 ///<summary>
 ///The server sends information to the client
 ///</summary>
 ///<param name="sender"></param>
 ///<param name="e"></param>
 private void btnsend_click_1 (object sender, eventargs e)
 {
 if (combobox1.selecteditem == null) //If the combobox control has no selected value.
Prompt the user to choose a client
 {
 messagebox.show ("Please select a client");
 return;
 }
 string str=txtmes.text;//Get the content entered by the user (the information the server wants to send to the client)
 byte [] strbyte=encoding.default.getbytes (str);//Convert information into a binary byte array
 string getip=combobox1.selecteditem as string;//combobox stores the client (ip + port number)
 socket socketsend=dic [getip] as socket;//According to this (ip and port number), find the corresponding dic key-value pair Assign a socket to communicate with the client
 socketsend.send (strbyte);//Send information to the client
 }
 }
}

Open the start command cmd telnet 10.18.16.46 5000 which is the IP address of the telnet server.

c
  • Previous C # winform programming in response to the return key implementation code
  • Next Full-screen preview of picture click in IOS