Dotnet (C #) socket BASIC Programming
Last Update:2017-02-28
Source: Internet
Author: User
Programming Socket BASIC Programming
Service side:
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading;
Thread Mythread;
Socket socket;
Clean up all resources that are in use.
protected override void Dispose (bool disposing)
{
Try
{
Socket. Close ()//Free resources
Mythread. Abort ()//Abort 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[100];
This.label1.text=iep. ToString ();
Socket. Bind (IEP);
Todo
while (true)
{
Try
{
Socket. Listen (5);
Socket Newsocket=socket. Accept ();
Newsocket.receive (Bytemessage);
String stime = DateTime.Now.ToShortTimeString ();
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 Button1_Click (object sender, System.EventArgs e)
{
Try
{
Mythread = new Thread (new ThreadStart (Beginlisten));
Mythread. Start ();
}
catch (System.Exception er)
{
MessageBox.Show (Er. Message, "complete", messageboxbuttons.ok,messageboxicon.stop);
}
}
Client:
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
private void Button1_Click (object sender, System.EventArgs e)
{
BeginSend ();
}
private void BeginSend ()
{
String Ip=this.txtip.text;
String Port=this.txtport.text;
IPAddress Serverip=ipaddress.parse (IP);
int Serverport=convert.toint32 (port);
IPEndPoint iep=new IPEndPoint (serverip,serverport);
Byte[] Bytemessage;
Todo
// {
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);
}
Sending and receiving terminals based on TCP protocol
Receiving end of TCP protocol
Using System.Net.Sockets; Use to Tcplisten class
Using System.Threading; Use to Thread
Using System.IO; Use to StreamReader class
int port = 8000; Define the listening port number
Private Thread Ththreadread; Create threads to listen for port numbers, receive information
Private TcpListener Tltcplisten; Listening port number
private bool Blistener = true; Set the indicator bit to determine the listening state
Private NetworkStream Nsstream; Create a 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; Reading data from the network underlying data stream
Private TcpClient tcclient;
private void Listen ()
{
Try
{
Tltcplisten = new TcpListener (port); Initializes the TcpListener instance with a 8000 port number
Tltcplisten.start (); Start listening.
Statusbar1.text = "is listening ...";
Tcclient = Tltcplisten.accepttcpclient (); Request via TCP connection
Nsstream = Tcclient.getstream (); Gets the network underlying data stream that is used to send and receive data
Srread=new StreamReader (Nsstream)//To initialize the StreamReader instance with the resulting network underlying data stream
Statusbar1.text = "Already connected!" ";
while (Blistener)//circular Listening
{
String smessage = Srread.readline ();//reading a row of data from the network underlying data stream
if (smessage = = "STOP")//Determine if the Disconnect TCP connection control code
{
Tltcplisten.stop (); Turn off listening
Nsstream.close (); Releasing resources
Srread.close ();
Statusbar1.text = "The connection has been closed!" " ;
Ththreadread.abort (); Abort thread
Return
}
String stime = DateTime.Now.ToShortTimeString (); Gets the time when the data is received
LISTBOX1.ITEMS.ADD (stime + "" + smessage);
}
}
catch (System.Security.SecurityException)
{
MessageBox.Show ("Listening failed!") "," wrong ");
}
}
Start listening.
private void Button1_Click (object sender, System.EventArgs e)
{
Ththreadread = new Thread (new ThreadStart (Listen));
Ththreadread.start ()//Start thread
Button1. Enabled=false;
}
Clean up all resources that are in use.
protected override void Dispose (bool disposing)
{
Try
{
Tltcplisten.stop (); Turn off listening
Nsstream.close ();
Srread.close ()//Releasing Resources
Ththreadread.abort ()//Abort thread
}
catch{}
if (disposing)
{
if (Components!= null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing);
}
Sending end of TCP protocol
Using System.Net.Sockets; Use to Tcplisten class
Using System.Threading; Use to Thread
Using System.IO; Use to StreamWriter class
Using System.Net; Use IPAddress class, Iphostentry class, etc.
Private StreamWriter Swwriter; Used to spread data to the network's underlying data
Private NetworkStream Nsstream; Create a network underlying data stream for sending data
Private TcpClient 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; It implements a TCP connection request to a remote host
private bool Tcpconnect = false; Defines identifiers that indicate whether a TCP connection is established
Connection
private void Button1_Click (object sender, System.EventArgs e)
{
IPAddress Ipremote;
Try
{
Ipremote = Ipaddress.parse (TextBox1.Text);
}
Catch//Judge the legality of a given IP address
{
MessageBox.Show ("The IP address entered is illegal!") "," the wrong hint! " ) ;
return;
}
Iphostentry Iphost;
Try
{
Iphost = Dns.resolve (TextBox1.Text);
}
Catch//Determine whether the IP address corresponds to the host online
{
MessageBox.Show ("Remote host is not on line!") "," the wrong hint! " ) ;
return;
}
string shostname = Iphost.hostname;
Try
{
TcpClient tcpclient = new TcpClient (shostname,8000)//TCP connection request for 8000 port of remote host
Nsstream = Tcpclient.getstream ()//request, and get the network underlying data stream for transferring data
Swwriter = new StreamWriter (nsstream), or//using the obtained network underlying data stream to initialize the StreamWriter instance
Button1. Enabled = false;
Button2. Enabled = true;
Tcpconnect = true;
Statusbar1.text = "Already connected!" " ;
}
Catch
{
MessageBox.Show ("Cannot establish a connection with the remote host 8000 port!") "," the wrong hint! " ) ;
return;
}
}
Send
private void Button2_Click (object sender, System.EventArgs e)
{
if (TextBox2.Text!= "")
{
Swwriter.writeline (TextBox2.Text)//Refresh data in current data stream
Swwriter.flush ();
}
Else
{
MessageBox.Show ("Send message cannot be empty!") "," the wrong hint! ");
}
}
Clean up all resources that are in use.
protected override void Dispose (bool disposing)
{
if (Tcpconnect)
{
Swwriter.writeline ("STOP"); Send control code
Swwriter.flush (); Refreshing data in the current data stream
Nsstream.close (); Clear Resources
Swwriter.close ();
}
if (disposing)
{
if (Components!= null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing);
}