C # Socket Network Programming example

Source: Internet
Author: User

The example in this paper describes the C # socket network programming techniques. Share to everyone for your reference. The specific analysis is as follows:

The client wants to connect to the server: first know the IP address of the server. And the server has a lot of applications, each of which corresponds to a port number

So the client wants to communicate with an application on the server and must know the IP address of the server where the application resides, and the port number the application corresponds to.


TCP protocol:

Security and stability, generally do not occur data loss, but inefficient. Using TCP to occur data generally after 3 handshake (all inefficient, self-Baidu three times handshake)


UDP protocol:

Fast, efficient, but unstable, prone to data loss (no three handshake, no matter the server is empty, information all to the server, all the efficiency, but the server is busy when there is no way to process your data, easy to cause data loss, instability)


The code is as follows:

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 you click Start listening, create a socket on the server that is responsible for listening for IP addresses and port numbers.

Socket Socketwatch = new socket (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP);

Any: Provides an IP address that indicates 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 on the server side

IPEndPoint point = new IPEndPoint (IP, Convert.ToInt32 (txtport.text));

Listening

Socketwatch.bind (point);

ShowMsg ("monitor success");

Socketwatch.listen (10);//The maximum length of the connection queue, i.e., the maximum number of clients that can be connected in a single point in time, queued for longer than the length

Wait for the client to connect; Accept () This method can receive the client's connection and create a socket for the new connection that is responsible for the communication

Thread th = new Thread (Listen); A method that is executed by a thread must be of type object if it has parameters.

Control.checkforillegalcrossthreadcalls = false; Because. NET does not allow cross-thread access, this cancels cross-thread checking.. NET does not check for cross-thread access, and all will not be reported: "This error has been accessed from the thread that did not create the control" Txtlog ", which enables cross-thread access

Th. IsBackground = true; Cheng the th line as a background thread.

Start (object parameter); Parameter: An object that contains the data that the thread executes the method to use, that is, the thread executes the Listen method, listen parameters

Th.  Start (Socketwatch); The arguments in this parenthesis are actually parameters of the listen () method. Because the thread th = new Thread (Listen) can only write the method name (the function name) in this parenthesis, but the Listen () method is parameter, all the arguments are to be added in the start () method.

}

<summary>

Wait for the client to connect and create a socket to communicate with if the client connection is monitored

</summary>

<param name= "O" ></param>

void Listen (Object o)//Why not pass the socket type parameter directly here? The reason is that if the method executed by the thread has parameters, the argument must be of type Object

{

Socket Socketwatch = o as socket;

while (true)//Why is there a while loop here? Because when a person connects in and creates a socket that communicates with it, the program executes down, and then does not come back to create a socket for communication for the second person's connection. (It should be everyone (each client) to create a socket to communicate with) so write in the loop.

{

Wait for the client to connect; Accept () This method can receive the client's connection and create a socket for the new connection that is responsible for the communication

Socket socketsend = socketwatch.accept ();

Dic. ADD (SocketSend.RemoteEndPoint.ToString (), socketsend); (based on the client's IP address and port number to find the socket responsible for communication, each client corresponds to a socket responsible for communication), IP address and port number as the key, the socket responsible for communication as a value to the DIC key value pairs.

We are able to get the IP address and port number of the remote connected client through a Remoteendpoint property of this Socketsend object responsible for communication.

ShowMsg (socketSend.RemoteEndPoint.ToString () + ":" + "connection successful");//Effect: 192.168.1.32: Connection Successful

COMBOBOX1.ITEMS.ADD (SocketSend.RemoteEndPoint.ToString ()); Add each client that is connected to the Combbox control.

After the client connection succeeds, the server should receive a message 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 by 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 first in a byte array.

byte[] buffer = new BYTE[1024 * 1024 * 2]; Creates a byte array with a length of 2M

The number of valid bytes actually received; (The Receive method receives data from the client and then saves the data to a buffer byte array, returning the length of the data received)

int r = socketsend.receive (buffer);

if (r = = 0)//If the number of valid bytes received is 0, the client is closed. This is the time to jump out of circulation.

{

Only the client sends a message to the user, it is not possible to send 0 bytes in length. Even if the message is empty, the empty message has a length. A valid byte length of 0 for all received means that the client has closed

Break

}

The data in this byte array of buffer is decoded into a string type that we can read by UTF8, because the actual length of the data stored in buffer is R, so it starts decoding from the byte with index 0, decoding the length of r bytes 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 Txtlog text box.

}

<summary>

Server sends message to 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 value selected. The user is prompted to select the client

{

MessageBox.Show ("Please select Client");

Return

}

string str = Txtmes.text; Get user input (information that the server wants to send to the client)

byte[] Strbyte = Encoding.Default.GetBytes (str); Converting information into binary byte arrays

String getip = Combobox1.selecteditem As String; The ComboBox stores the client (ip+ port number)

Socket socketsend = Dic[getip] as socket; According to this (IP and port number) go to DIC key value pairs to find the corresponding assignment and client communication socket "Each client has a socket that is responsible for communicating with it"

Socketsend.send (Strbyte); Sending information to the client

}

}

}

Start command cmd telnet 10.18.16.46 5000 that is the port number of the Telnet server IP address binding

I hope this article is helpful to everyone's C # programming.

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
C # Socket Network Programming example

This address: http://www.paobuke.com/develop/c-develop/pbk23169.html






Related content VS2012 Program packaging deployment Graphic Analysis The application of memo pattern in C # design pattern Programming C #, the method of writing data to a file by Stream C #, ASP. NET Universal Extension Tool class Typeparse
Example analysis of array segment usages in C #??? Úxa ¢ó? ¨?ê?ac# feature-Object collection initializer describes DevExpress implementing a method for setting watermark text for TextEdit

C # Socket Network Programming example

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.