C # Socket programming and C # How to use multithreading

Source: Internet
Author: User

Last summer I spent a few months studying asp.net and got C # socket in the last few weeks. I know a little bit about it. I haven't moved C # For A Long Time. Although I am not interested in this language, I still recall my memories and forget it.

C # Socket:

It is recommended that cainiao who are new to C # socket do not use TcpListenner, TcpClient, and other MS encapsulated class libraries. These encapsulated classes are indeed convenient to use, but what have you learned after you use them? So what should I use? I only use Socket as a class. That's good, It will be troublesome,

However, in C #, even Socket and MS are encapsulated, making the Socket very simple to use, I wrote a very popular TCP chat program when I was just learning it. you can try the next multi-C chat program, TCP will be able to do a UDP.

UDP will be ready, learn SMTP, ah, SMTP is encapsulation too powerful, all become silly, then you can look at the MultiThread, that is, multithreading, these are almost the same, you can try to write a Proxy. I learned it like this at the time, but I am just a cainiao. Now I am engaged in asm/c/C ++ and I forgot about it.

The first two namespaces must be included:

Using System. Net;

Using System. Net. Sockets;

Several frequently-used classes: (these items are detailed after you check MSDN)

IPHostEntry, Dns, IPAddress, IPEndPoint, and the most important Socket

IPEndPoint: This is the network endpoint. It is a fixed address on the Network: a combination of an IP address and a port.

Next I will use a simple chat program I wrote as an example (short code)

Form1.cs

// Note that this is an integration of Server and Client.

Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Text;
Using System. Windows. Forms;
Using System. Net;
Using System. Net. Sockets; // This is required to use Socket.
Using System. IO;
Using System. Threading; // This is required for multithreading.

Namespace OnlySocket
{
Public partial class Form1: Form // partial indicates that this code is only part of the Form1 class. The Form1 class inherits from the Form class.
{
Public Form1 ()
{
InitializeComponent (); // constructor to initialize the container.
}
Socket sock; // defines the object of a Socket class (protected by default)
Thread th; // defines the object of a Thread class
//

Public static IPAddress GetServerIP () // static function, which can be called without instantiation.
{
IPHostEntry ieh = Dns. GetHostByName (Dns. GetHostName (); // no more static functions of the Dns class

// Or use DNS. Resolve () instead of GetHostName ()
Return ieh. AddressList [0]; // return an instance of the Address class. It is not surprising that AddressList is an array. A Server may have n ip addresses.
}

Private void BeginListen () // Socket listener function, which is used as a parameter to create a new thread.
{
IPAddress serverIp = GetServerIP (); // call the static function GetServerIP to obtain the local IPAddress.
IPEndPoint iep = new IPEndPoint (serverIp, Convert. ToInt32 (tbPort. Text); // local endpoint
Sock = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp); // instantiate the sock Member
Byte [] byteMessage = new Byte [100]; // The Byte array buffer for storing messages. Note that the array representation method is different from that of C.
This. lbIep. Text = iep. ToString ();
Sock. Bind (iep); // an important function of the Socket class, bound to an IP address,
While (true) // here, an endless loop is set to listen to the port. Some people will ask the endless loop, so the program will not get stuck. Note that this is only a class, there is no main function yet.
{
Try
{
Sock. Listen (5); // OK, the sock can start listening after it is bound to a local endpoint. 5 indicates that the maximum number of connections is 5.
Socket newSock = sock. accept (); // an important method of the Socket class: Accept, which accepts Socket connection requests from outside and returns a Socket, this socket starts to process the conversation between this client and the Server.
NewSock. Receive (byteMessage); // Save the data sent by the client to the buffer zone.
String msg = "From [" + newSock. remoteEndPoint. toString () + "]:" + System. text. encoding. UTF8.GetString (byteMessage) + "\ n"; // The GetString () function converts the byte array to the string type.
RtbTalk. AppendText (msg + "\ n"); // display it in the text Control
}
Catch (SocketException se) // catch an exception,
{
LbState. Text = se. ToString (); // display it. You can also customize the error here.
}
}
}

Private void btConnect_Click (object sender, EventArgs e) // event triggered by the connection button: connect to the Server
{
BtConnect. Enabled = false;
BtStopConnect. Enabled = true;
Try
{
Th = new Thread (new ThreadStart (BeginListen); // create a new Thread for processing listening. This statement can be written separately, for example: threadStart ts = new ThreadStart (BeginListen); th = new Thread (ts); however, note that the parameters of the ThreadStart constructor must be functions without parameters. the function name here is actually its pointer. Is it a delegate here?
Th. Start (); // Start the thread
LbState. Text = "Listenning ...";
}
Catch (SocketException se) // handle exceptions
{
MessageBox. Show (se. Message, "problem occurred", MessageBoxButtons. OK, MessageBoxIcon. Information );
}
Catch (ArgumentNullException AE) // an exception occurs when the parameter is null.
{
LbState. Text = "parameter error ";
MessageBox. Show (AE. Message, "error", MessageBoxButtons. OK, MessageBoxIcon. Warning );
}

}

Private void btStopConnect_Click (object sender, EventArgs e) // stop the listener
{
BtStopConnect. Enabled = false;
BtConnect. Enabled = true;
Sock. Close (); // Close the socket
Th. Abort (); // terminate the listening thread

LbState. Text = "Listenning stopped ";
}

Private void btExit_Click (object sender, EventArgs e)
{
Sock. Close ();
Th. Abort ();
Dispose (); // clear the resource, that is, release the memory.
This. Close (); // Close the dialog box and exit the program.
}

Private void btSend_Click (object sender, EventArgs e)
{
Try
{
IPAddress clientIp = IPAddress. Parse (tbTargetIp. Text); // static function Parse () of IPAddress class: converts Text to an instance of IPAddress.
Int clientPort = Convert. ToInt32 (tbPort. Text); // These conversion functions of C # are very convenient, not as troublesome as C ++.
IPEndPoint clientIep = new IPEndPoint (clientIp, clientPort); // It is not very good to use client here ....,
Byte [] byte_Message;
Socket socket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); there are many parameters during instantiation. This is Tcp. the SocketType of Tcp is Stream: Data Stream. If the protocol type is UDP, It is data packet transmission, and QQ is UDP.
Socket. Connect (clientIep); // another function of Socket Connect (IPEndPoint). Connect to a remote socket
Byte_Message = System. Text. Encoding. UTF8.GetBytes (rtbWords. Text); // It is used if UTF8 supports Chinese characters.
Socket. Send (byte_Message );
RtbTalk. AppendText ("\ n" + "My words:" + rtbWords. Text + "\ n ");
Socket. Shutdown (SocketShutdown. Both );
Socket. Close ();
}
Catch (ArgumentNullException AE)
{
MessageBox. Show (AE. Message, "parameter is blank", MessageBoxButtons. OKCancel, MessageBoxIcon. Information );
}
Catch (SocketException se)
{
MessageBox. Show (se. Message, "problem occurred", MessageBoxButtons. OK, MessageBoxIcon. Information );
}
}

}
}

Program. cs

Using System;
Using System. Collections. Generic;
Using System. Windows. Forms;

Namespace OnlySocket
{
Static class Program
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Static void Main () // here is the main function.

{
Application. EnableVisualStyles ();
Application. SetCompatibleTextRenderingDefault (false );
Application. Run (new Form1 ());
}
}
}

I have been writing for a long time, and I am tired enough. Although it is basic, I also reviewed it when I wrote it myself.

In fact, I am not very familiar with multithreading myself. I remember I wrote a multi-threaded scanner last summer. I don't know why. It would be very depressing to have a thread open above 50. in fact, at that time, I implemented it using new Thread = Thread (new ThreadStart (Fun), and the method was very clumsy.

The code is like this:

First write a Scan class:

Public class Scan

{

Try {public Scan () {... Init ...}

Public void Scan {... task cyclic Scan...} // IP address and port in the task struct, and whether fLag has been scanned}

Catch {}

}

Then the main function can do this:

Scan [] Scan = new Scan [XX]

Thread [] thread = new Thread [XX];
For (int I = 0; I <XX; I ++)
{
Topology [I] = new Scan (this, I );
Thread [I] = new Thread (new ThreadStart (threads [I]. StartScan ));
Thread [I]. Start ();

}

In this way, you can simply implement multiple threads.

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.