To add a using instruction set:
Using System.Net.Sockets;
Using System.Threading;
Using System.Net;
Add definition (IP address IP interface Berkeley socket Interface):
Private IPAddress ServerIP = Ipaddress.parse ("127.0.00.1");
Private IPEndPoint serverfulladdr;
Private Socket sock;
Disconnect:
Disconnect
private void btnClose_Click (object sender, EventArgs e)
{
sock. Close ();
Btnconn.enabled = true;
}
To connect to a server:
Connection server-side
private void Btnconn_click (object sender, EventArgs e)
{
btnconn.enabled = false;
ServerIP = Ipaddress.parse (tbxip.text);
Try
{
serverfulladdr = new IPEndPoint (serverip, Int. Parse (Tbxport.text));/Set IP, port
sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, PROTOCOLTYPE.TCP);
Specifies the local host address and port number
sock. Connect (SERVERFULLADDR);
btnconn.enabled = false;
Lblerror.text = "Connection server succeeded ...." ";
Btnclose.enabled = true;
Sock. Close ();
}
catch (Exception ee)
{
btnconn.enabled = true;
Lblerror.text = "Connection Server failed ... Please carefully check that the server is open "+ ee;
}"
Send message:
Send Message private void Btnsend_click (object sender, EventArgs e) {serverfulladdr = new Ipendpoin T (serverip, Int. Parse (Tbxport.text));/Set IP, Port sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.t
CP); Specifies the local host address and port number sock.
Connect (SERVERFULLADDR);
byte[] Bytesend = System.Text.Encoding.Default.GetBytes (This.tbxMessage.Text);
byte[] message = new byte[1024];
String mess = "";
int bytes = 0; try {//Send data sock.
Send (Bytesend); bytes = sock. Receive (message)//receiving data Mess = Mess + Encoding.Default.GetString (message,0,bytes);//encoding (when the bytes received are greater than 1024 this should is a loop receive, the test is not written like that)//do//{//bytes = newsocket.receive (message, message .
Length, 0);
Mess = mess + Encoding.ASCII.GetString (message, 0, bytes); }//while (Bytes > 0);
Tbxmessage.text = mess;
The catch (Exception ex) {Lblerror.text = "error occurred, please contact Administrator" +EX; } sock.
Close (); }
Empty message:
Empty message
private void Btnclean_click (object sender, EventArgs e)
{
tbxmessage.text = "";
}
Receive data (for multithreading reasons, a little bit of trouble):
1. Open Thread
Thread mythead = null;
2. Thread function, similar to specifying interrupt service function
Mythead = new Thread (new ThreadStart (Beginlisten));
Mythead.start ();
3. Write functions (this part of the understanding is more cumbersome, involving delegates, because if the control used to display data is open in the main thread, and the default value of the control is not available across threads, it requires a delegate.) )
A. The Invoke function needs to be well understood: he is executing the specified delegate with the specified argument list on the thread that owns the control's underlying window handle. The popular point is that I delegate the thread that owns this control to help me perform this operation.
B. Why use the Accept function. Create a new socket for the new connection. Understood as: Sock This socket is already listening, and the number of incoming connections allowed in the queue is multiple, so a new socket is created, and when there is a busy incoming connection in the queue, the address is given to the new socket to recieve the data. efficient, stable some.
private void Beginlisten () {SERVERI2.XIANP = Ipaddress.parse (Tbxip.text); IP serverfulladdr = new IPEndPoint (serverip, Int. Parse (Tbxport.text));/Set IP, Port sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.t
CP); Specifies the local host address and port number sock.
Bind (SERVERFULLADDR);
Lbxmessage.invoke (New Settextcallback (SetText), "Start successful time:" + DateTime.Now, 1);
byte[] message = new byte[1024];
String mess = ""; while (true) {try {sock.
Listen (5); The//backlog parameter specifies the maximum number of incoming connections that can be accommodated in the queue. Socket Newsocket = sock. Accept ()//creates a new socket for the new connection.
Sock This socket is used for listening, when he has a connection request, the address to the new socket to receive, so that does not affect his continued monitoring of the original socket. int bytes = newsocket.receive (message);//using just Chuangjian receive data mess = Encoding.Default.GetString (message, 0, bytes)//To receive byte encoding (s and c both ends encoded format must be consistent otherwise Chinese garbled) (when receivingWhen the byte is greater than 1024, this should be a circular receipt, and the test is not written like that. Lbxmessage.invoke (new Settextcallback (SetText), mess, 1);//child thread operation main thread U I control//Get client IP and port string ip11 = NewSocket.RemoteEndPoint.AddressFamily.ToString ()
; Mess = "Received data:" + Mess + "from:" +ip11+ "Current time is:" + datetime.now; Process Data Newsocket.send (Encoding.Default.GetBytes (Mess));//Send data to client} C Atch (socketexception se) {lbxmessage.invoke (new Settextcallback (SetText), mess + SE,
1); }} #region//Reputation delegate object, can be understood as a function pointer delegate void Settextcallback (s
Tring text, int num); To pass the method, she has the same parameters and return value type private void SetText (string text, int num) {LBXMESSAG with comparedelegate
E.items.add (text); } #endregion
A complete demo of the reference:
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Windows.Forms;
Using System.Net;
Using System.Net.Sockets;
Using System.IO;
Using System.Threading; namespace Tcpclienttest {public partial class Formmain:form {public FormMain () {I
Nitializecomponent (); } private void Formmain_load (object sender, EventArgs e) {//Initialize control txtsendmssg.t
ext = "test data";
Open listener Start listening thread thrlistener = new Thread (new ThreadStart (Listen));
Thrlistener.start (); private void Formmain_formclosing (object sender, FormClosingEventArgs e) {//force close program (forcibly terminating Li
Stener) environment.exit (0);
}//Send data private void Btnsend_click (object sender, EventArgs e) { TcpClient tcpclient = new TcpClient ();
Tcpclient.connect (Ipaddress.parse ("170.0.0.78"), 2014);
Tcpclient.connect (Ipaddress.parse ("127.0.0.1"), 2014);
NetworkStream Ntwstream = Tcpclient.getstream ();
if (ntwstream.canwrite) {byte[] bytsend = Encoding.UTF8.GetBytes (Txtsendmssg.text);
Ntwstream.write (bytsend, 0, bytsend.length);
else {MessageBox.Show ("cannot write data stream");
Ntwstream.close ();
Tcpclient.close ();
Return
} ntwstream.close ();
Tcpclient.close (); }//Listener data private void Listen () {Socket listener = new Socket (addressfamily.internet
Work, SocketType.Stream, protocoltype.tcp); Listener.
Bind (New IPEndPoint (Ipaddress.any, 2014)); Continuously listening on port while (true)
{Listener.
Listen (0); Socket socket = listener.
Accept ();
NetworkStream Ntwstream = new NetworkStream (socket);
StreamReader Strmreader = new StreamReader (ntwstream);
Invoke (New Printrecvmssgdelegate (PRINTRECVMSSG), new object[] {strmreader.readtoend ()}); Socket.
Close (); }//The listener of the program has not closed//listener.
Close ();
}//thread to add a string to the text box TXTRECVMSSG and delegate private delegate void Printrecvmssgdelegate (string s); private void PRINTRECVMSSG (string info) {Txtrecvmssg.text = string.
Format ("[{0}]:{1}\r\n", DateTime.Now.ToLongTimeString (), info); }
}
}