. Simple example of socket programming in net

Source: Internet
Author: User
Tags exit empty socket socket error thread time interval tostring port number
Programming | example

The following example program implements simple socket communication and can open multiple clients. The native test passed and no online tests were made.

Server:

Using System.Net;

Using System.Net.Sockets;

Using System.Threading;

Using System.Collections;

Namespace MySocketServer1

{

public partial class Form1:form

{

Private IPAddress ServerIP = Ipaddress.parse ("127.0.0.1");

Private IPEndPoint serverfulladdr;//Full terminal address

Private Socket sock;

Private System.Timers.Timer MyTimer;

Private ArrayList alsock;//for saving connections when multiple connections are established

Public Form1 ()

{

InitializeComponent ();

}

private void Btstart_click (object sender, EventArgs e)

{

SERVERFULLADDR = new IPEndPoint (ServerIP, 1000);/Fetch port number 1000

Constructs a socket object with a socket type of "stream socket" that specifies the protocol element in a five-tuple

Sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream,

PROTOCOLTYPE.TCP);

Specify a local two dollar in the five-tuple, which is the local host address and port number

Sock. Bind (SERVERFULLADDR);

To listen for incoming connections, specify a maximum of 20 for a pending connection queue

Sock. Listen (20);

Alsock = new ArrayList ();

Construction timer with a time gap of 1 seconds, that is, every second accept () method is executed to get the first pending connection request in the connection request queue

MyTimer =new System.Timers.Timer (1000);

mytimer.elapsed +=new System.Timers.ElapsedEventHandler (mytimer_elapsed);

Mytimer.enabled = true;

}

private void Mytimer_elapsed (object sender, System.Timers.ElapsedEventArgs e)

{

mytimer.enabled = false;

Executes accept () that will block this thread when the pending queue is empty, and the timer will stop because of the previous statement, direct//to incoming

Socket Acceptsock = sock. Accept ();

Deposit the socket object generated by accept () into ArrayList

Alsock.add (Acceptsock);

Constructs the Threading.timer object, which causes the program to restart the thread. The thread executes the callback function, and the delegate limit//function argument must be an object type. The second parameter of the Threading.timer constructor, which is the parameter of the incoming callback function, specifies the delay before the callback function is invoked, 0 starts immediately, and the last parameter specifies the time interval to invoke the callback function//, and 0 is executed only once.

System.Threading.Timer ti = new System.Threading.Timer (new

TimerCallback (receivemsg), Acceptsock, 0, 0);

Mytimer.enabled = true;

}

private void Receivemsg (Object obj)

{

Socket Acceptsock = (socket) obj;

Try

{

while (true)

{

byte[] ByteArray = new byte[100];

Acceptsock.receive (ByteArray);//Receive Data

To turn a byte array into a string

String Strrec = System.Text.Encoding.UTF8.GetString (ByteArray);

if (this.rtbReceive.InvokeRequired)

{

This.rtbReceive.Invoke (this.) New EventHandler (this. Changericktextbox), New

Object[] {strrec, eventargs.empty});

}

}

}

catch (Exception ex)

{

Acceptsock.close ();

MessageBox.Show ("s:receive message Error" +ex. message);

}

}

private void Changericktextbox (Object Obj,eventargs e)

{

string s = System.Convert.ToString (obj);

This.rtbReceive.AppendText (s + environment.newline);

}

private void Btsend_click (object sender, EventArgs e)

{

Socket Sc=null;

byte[] Bytesend =

System.Text.Encoding.UTF8.GetBytes (This.tbSend.Text.ToCharArray ());

Try

{

When there are several client connections, enter which connection to send in TextBox1

int index = Int. Parse (This.textBox1.Text.Trim ());

sc = (Socket) alsock[index-1];

Send data

Sc. Send (Bytesend);

}

catch (Exception ex)

{

if (sc!= null)

{

Sc. Close ();

}

MessageBox.Show ("s:send message Error" +ex. message);

}

}

private void Btclose_click (object sender, EventArgs e)

{

Try

{

Application.exit ();

}

catch (Exception ex)

{

MessageBox.Show ("S:close Socket Error" + ex.) message);

}

}

}

}

== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==

Client:

Using System.Net;

Using System.Net.Sockets;

Using System.Threading;

Namespace MySocketClient1

{

public partial class Form1:form

{

Private IPAddress ServerIP = Ipaddress.parse ("127.0.0.1");

Private IPEndPoint serverfulladdr;

Private Socket sock;

Public Form1 ()

{

InitializeComponent ();

}

private void Btconnect_click (object sender, EventArgs e)

{

Try

{

SERVERFULLADDR = new IPEndPoint (ServerIP, 1000);

Sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream,

PROTOCOLTYPE.TCP);

Sock. Connect (serverfulladdr);//Establish a connection to a remote host

Start a new thread to receive data

Thread t = new Thread (new ThreadStart (receivemsg));

T.name = "Receive message";

A thread is either a background thread or a foreground thread. The background thread is similar to the foreground thread, except that the background line//thread does not prevent the process from terminating. Once all foreground threads belonging to a process terminate, the common language runtime ends the process by calling Abort on any still active background thread.

T.isbackground = true;

T.start ();

}

catch (Exception ex)

{

MessageBox.Show (ex. message);

}

}

private void Receivemsg ()

{

Try

{

while (true)

{

byte[] Byterec = new byte[100];

This.sock.Receive (BYTEREC);

String Strrec = System.Text.Encoding.UTF8.GetString (BYTEREC);

if (this.rtbReceive.InvokeRequired)

{

This.rtbReceive.Invoke (New EventHandler (CHANGERTB), new object[]

{Strrec, eventargs.empty});

}

}

}

catch (Exception ex)

{

MessageBox.Show ("Receive message Error" +ex.) message);

}

}

private void Changertb (Object obj, EventArgs e)

{

string s = System.Convert.ToString (obj);

This.rtbReceive.AppendText (s + environment.newline);

}

private void Btsend_click (object sender, EventArgs e)

{

byte[] Bytesend =

System.Text.Encoding.UTF8.GetBytes (This.tbSend.Text.ToCharArray ());

Try

{

This.sock.Send (Bytesend);

}

Catch

{

MessageBox.Show ("Send message Error");

}

}

private void Btclose_click (object sender, EventArgs e)

{

Try

{

This.sock.Shutdown (socketshutdown.receive);

This.sock.Close ();

Application.exit ();

}

Catch

{

MessageBox.Show ("Exit Error");

}

}

}

}

Puzzled by:

Client-side Red Callout statement: This.sock.Shutdown (socketshutdown.receive), if changed to

This.sock.Shutdown (Socketshutdown.both) or This.sock.Shutdown (socketshutdown.send);

When the Cloce button is clicked, CPU usage goes up to 100% and uses This.sock.Shutdown (socketshutdown.receive);

Or do not call the shutdown () method, this problem does not. Should the client not use shutdown ()?



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.