DOTNET (C #) Basic socket programming)

Source: Internet
Author: User
Tags getstream
Http://blog.csdn.net/itfly8/archive/2006/03/13/622877.aspx

Basic socket programming

Server:

Using system. net;

Using system. net. Sockets;

Using system. text;

Using system. Threading;

 

Thread mythread;

Socket socket;

// Clear all resources in use.

Protected override void dispose (bool disposing)

{

Try

{

Socket. Close (); // release resources

Mythread. Abort (); // abort a thread

}

Catch {}

 

If (disposing)

{

If (components! = NULL)

{

Components. Dispose ();

}

}

Base. Dispose (disposing );

}

Public static IPaddress getserverip ()

{

Iphostentry IEH = DNS. gethostbyname (DNS. gethostname ());

Return IEH. Addresslist [0];

}

Private void beginlisten ()

{

IPaddress serverip = getserverip ();

Ipendpoint IEP = new ipendpoint (serverip, 8000 );

Socket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );

 

Byte [] bytemessage = new byte [1, 100];

This. label1.text = IEP. tostring ();

Socket. BIND (IEP );

// Do

While (true)

{

Try

{

Socket. Listen (5 );

Socket newsocket = socket. Accept ();

Newsocket. Receive (bytemessage );

 

String stime = datetime. Now. tow.timestring ();

String MSG = stime + ":" + "Message from :";

MSG + = newsocket. remoteendpoint. tostring () + encoding. Default. getstring (bytemessage );

This. listbox1.items. Add (MSG );

 

}

Catch (socketexception ex)

{

This. label1.text + = ex. tostring ();

}

}

// While (bytemessage! = NULL );

}

// Start listening

Private void button#click (Object sender, system. eventargs E)

{

Try

{

Mythread = new thread (New threadstart (beginlisten ));

Mythread. Start ();

 

}

Catch (system. Exception ER)

{

MessageBox. Show (ER. message, "finished", messageboxbuttons. OK, messageboxicon. Stop );

}

}

 

 

Client:

 

Using system. net;

Using system. net. Sockets;

Using system. text;

 

Private void button#click (Object sender, system. eventargs E)

{

Beginsend ();

}

Private void beginsend ()

{

String ipdomainthis.txt IP. text;

String portdeskthis.txt port. text;

 

IPaddress serverip = IPaddress. parse (IP );

Int SERVERPORT = convert. toint32 (port );

Ipendpoint IEP = new ipendpoint (serverip, SERVERPORT );

Byte [] bytemessage;

// Do

//{

Socket socket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );

Socket. Connect (IEP );

 

Bytemessage = encoding. ASCII. getbytes (textbox1.text );

Socket. Send (bytemessage );

Socket. Shutdown (socketshutdown. Both );

Socket. Close ();

//}

// While (bytemessage! = NULL );

}

 

Transmission and receiving end based on TCP protocol

 

TCP Receiver

 

Using system. net. Sockets; // use the tcplisten class

Using system. Threading; // use the thread

Using system. IO; // use streamreader class

 

Int Port = 8000; // define the listening port number

Private thread ththreadread; // creates a thread to listen on the port number and receive information.

Private tcplistener tltcplisten; // listener port number

Private bool blistener = true; // sets the flag bit to determine the listening status

Private networkstream nsstream; // create the received basic data stream

Private streamreader srread;

Private system. Windows. Forms. statusbar statusbar1;

Private system. Windows. Forms. Button button1;

Private system. Windows. Forms. ListBox listbox1; // read data from the basic network data stream

Private tcpclient tcclient;

 

Private void listen ()

{

Try

{

Tltcplisten = new tcplistener (port); // initialize the tcplistener instance on the port 8000

Tltcplisten. Start (); // start listening

Statusbar1.text = "listening ...";

Tcclient = tltcplisten. accepttcpclient (); // TCP Connection Request

Nsstream = tcclient. getstream (); // obtain the basic network data stream used to send and receive data

Srread = new streamreader (nsstream); // obtains the basic network data stream to initialize the streamreader instance.

Statusbar1.text = "connected! ";

 

While (blistener) // loop listener

{

String smessage = srread. Readline (); // read a row of data from the basic network data stream

If (smessage = "stop") // determines whether the TCP Connection Control code is disconnected.

{

Tltcplisten. Stop (); // disable listening

Nsstream. Close (); // release resources

Srread. Close ();

Statusbar1.text = "the connection has been closed! ";

Ththreadread. Abort (); // abort a thread

Return;

}

 

String stime = datetime. Now. tow.timestring (); // the time when the data is received.

Listbox1.items. Add (stime + "" + smessage );

}

}

Catch (system. Security. securityexception)

{

MessageBox. Show ("failed to listen! "," Error ");

}

}

// Start listening

Private void button#click (Object sender, system. eventargs E)

{

Ththreadread = new thread (New threadstart (Listen ));

Ththreadread. Start (); // start the thread

Button1.enabled = false;

}

// Clear all resources in use.

Protected override void dispose (bool disposing)

{

Try

{

Tltcplisten. Stop (); // disable listening

Nsstream. Close ();

Srread. Close (); // release resources

Ththreadread. Abort (); // abort a thread

}

Catch {}

 

If (disposing)

{

If (components! = NULL)

{

Components. Dispose ();

}

}

Base. Dispose (disposing );

}

 

Sending end of TCP protocol

 

Using system. net. Sockets; // use the tcplisten class

Using system. Threading; // use the thread

Using system. IO; // use streamwriter class

Using system. Net; // use the IPaddress class and iphostentry class.

 

Private streamwriter swwriter; // used to transmit data to the basic network data stream

Private networkstream nsstream; // create the network-based data stream for data transmission

Private tcpclient;

Private system. Windows. Forms. Button button1;

Private system. Windows. Forms. textbox textbox1;

Private system. Windows. Forms. Button button2;

Private system. Windows. Forms. textbox textbox2;

Private system. Windows. Forms. statusbar statusbar1;

Private system. Windows. Forms. Label label1;

Private system. Windows. Forms. Label label2; // submit a TCP connection request to the remote host.

Private bool tcpconnect = false; // defines the identifier to indicate whether a TCP connection is established.

 

// Connection

Private void button#click (Object sender, system. eventargs E)

{

IPaddress ipremote;

Try

{

Ipremote = IPaddress. parse (textbox1.text );

}

Catch // determine the validity of a given IP Address

{

MessageBox. Show ("The Entered IP address is invalid! "," Error message! ");

Return;

}

 

Iphostentry iphost;

Try

{

Iphost = DNS. Resolve (textbox1.text );

}

Catch // determine whether the host corresponding to the IP address is online

{

MessageBox. Show ("the remote host is not online! "," Error message! ");

Return;

}

 

String shostname = iphost. hostname;

Try

{

Tcpclient = new tcpclient (shostname, 8000); // apply for a TCP connection to port 8000 of the remote host

Nsstream = tcpclient. getstream (); // obtain the basic network data stream for data transmission through application

Swwriter = new streamwriter (nsstream); // use the obtained basic network data stream to initialize the streamwriter instance.

Button1.enabled = false;

Button2.enabled = true;

Tcpconnect = true;

Statusbar1.text = "connected! ";

}

Catch

{

MessageBox. Show ("cannot establish a connection with the remote host port 8000! "," Error message! ");

Return;

}

}

 

// Send

Private void button2_click (Object sender, system. eventargs E)

{

If (textbox2.text! = "")

{

Swwriter. writeline (textbox2.text); // refresh the data in the current data stream

Swwriter. Flush ();

}

Else

{

MessageBox. Show ("The message cannot be blank! "," Error message! ");

}

}

// Clear all resources in use.

Protected override void dispose (bool disposing)

{

If (tcpconnect)

{

Swwriter. writeline ("stop"); // send control code

Swwriter. Flush (); // refresh the data in the current data stream

Nsstream. Close (); // clear Resources

Swwriter. Close ();

}

If (disposing)

{

If (components! = NULL)

{

Components. Dispose ();

}

}

Base. Dispose (disposing );

}

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.