Socket network programming and socket network programming

Source: Internet
Author: User

Socket network programming and socket network programming

<.>

Connect the client to the server: First, you must know the IP address of the server. There are many applications in the server. Each application corresponds to a port number.
To communicate with an application on the server, the client must know the IP address of the server where the application is located and the port number corresponding to the application.

TCP protocol: secure and stable. Generally, data is not lost, but the efficiency is low. TCP data usually goes through three handshakes (low efficiency, Baidu three handshakes)
UDP protocol: fast, efficient, but unstable, data loss is prone to (no three handshakes have been performed, no matter the server is empty, all information is sent to the server, all efficiency is involved, however, when the server is busy, it cannot process your data, which may cause data loss and instability)

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.txt Port. text = "5000"; this.txt Ip. text = "192.168.137.1 ";} Private void btnStart_Click (object sender, EventArgs e) {// when you click Start to listen, create a Socket socketWatch = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // Any: provides an IP address that instructs the server to listen for client activities on all network interfaces. This field is read-only. IPAddress ip = IPAddress. any; // create a port number object; Set txtPort. set the value of the Text control to the server port number IPEndPoint = new IPEndPoint (ip, Convert. toInt32 (txtPort. text); // listen for socketWatch. bind (point); ShowMsg ("listener successful"); socketWatch. listen (10); // Maximum length of the connection queue; that is, a maximum of several clients can be connected in a time point. If the length is exceeded, a queue is established. // wait for the client to connect. Accept () this method can receive client connections and create a Socket Thread th = new Thread (Listen) responsible for communication for the new connection; // if the method to be executed by the Thread has parameters, the parameter must be of the object type Control. checkForIllegalCrossThr Eadcils = false; // because. net does not allow cross-thread access, the cross-Thread Check is canceled here .. Net does not check whether there is cross-thread access, so it will not report the error "never create a thread of the control" txtLog "to access it", thus implementing cross-thread access th. isBackground = true; // set th as the background thread. // Start (object parameter); parameter: an object that contains the data to be used by the method executed by the thread, that is, the Listen method executed by the thread and the th parameter of the Listen. start (socketWatch); // The parameters in this bracket are actually parameters of the Listen () method. Because Thread th = new Thread (Listen) can only write the method name (function name) in the brackets, but the Listen () method has parameters, and Start () is required for all () method to add its parameters} // <summary> // wait for the client to connect, if a client is connected, create a Socket to which the client communicates. /// </summary> /// <param name = "o"> </param> void Listen (object o) // Why is the Socket-type parameter not directly transmitted here? The reason is: if the method to be executed by the thread has a parameter, the parameter must be of the object type {Socket socketWatch = o as Socket; while (true) // Why is there a while loop here? This is because when a person creates a Socket to communicate with him, the program will be executed, and the Socket responsible for communication will not be created for the second person's connection. (It should be that each user (each client) creates a Socket to communicate with it) So it should be written in a loop. {// Wait for the client connection. The Accept () method can receive the client connection and create a Socket for communication for the new connection. socketSend = socketWatch. accept (); dic. add (socketSend. remoteEndPoint. toString (), socketSend); // (find the Socket responsible for communication based on the client's IP address and port number, each client corresponds to a Socket responsible for communication), IP address and port number as the key, fill the Socket responsible for communication as a value to the dic key-value pair. // We can obtain the IP address and port number of the remotely connected client ShowMsg (socketSend. remoteEndPoint. toString () + ":" + "connection successful"); // effect: 192.168.1.32: Connection successful comboBox1.Items. add (socketSend. remoteEndPoint. toString (); // Add each connected client to the combBox control. // After the client connection is successful, 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 sent from the client /// </summary> /// <param name = "o"> </param> void getData (object o) {while (true) {Socket socketSend = o as Socket; // put the data sent from the client into a byte array to byte [] buffer = new byte [1024*1024*2]; // create a byte array, byte array The length is 2 MB // the actual number of valid bytes received. (The Receive method is used to Receive data transmitted from the client and 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 disabled. This will jump out of the loop. {// Only the client sends messages to the user. It cannot be 0 bytes in length. Even if an empty message is sent, the empty message has a length. If the length of all valid bytes received is 0, the client has disabled break;} // encode the data in the byte array of buffer according to UTF-8, decodes the string type that we can understand. Because the actual length of data stored in the buffer array is r, the data is decoded from the byte with the index of 0, and r bytes are decoded in total. 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 str string to the TXT log text box.} /// <Summary> /// the service end sends a message 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 no value is selected for the comboBox control. The user is prompted to select the client {MessageBox. show ("select client"); return;} string str = txtMes. text; // get the content entered by the user (the information sent by the server to the client) byte [] strByte = Encoding. default. getBytes (str); // convert the information to a binary byte array string getIp = comboBox1.SelectedItem as string; // comboBox stores the client (ip + port number) socket socketSend = dic [getIp] as Socket; // based on this (ip address and port number) find the Socket with the corresponding value assigned to the client in the dic key-Value Pair [each client has a Socket responsible for communication with it] socketSend. send (strByte); // Send the information to the client }}}


Open the command cmd telnet 10.18.16.46 5000, that is, the port number bound to the telnet Server IP address.


Zookeeper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.