Client
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using System.Threading;
Using System.Net.Sockets;
Using System.Net;
Using System.Diagnostics;
Namespace Csocketclient
{
public partial class Main:form
{
Create 1 client sockets and one thread that listens for server requests
Thread threadclient = null;
Socket socketclient = null;
Public Main ()
{
InitializeComponent ();
StartPosition = Formstartposition.centerscreen;
To turn off illegal thread manipulation checks on a text box
Textbox.checkforillegalcrossthreadcalls = false;
this.btnSendMessage.Enabled = false;
This.btnSendMessage.Visible = false;
This.txtDebugInfo.Visible = false;
}
private void Form1_Load (object sender, EventArgs e)
{
}
private void Btnconnection_click (object sender, EventArgs e)
{
this.btnConnection.Enabled = false;
Definition of a socket listener
Socketclient = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);
Get the IP address in the text box
IPAddress address = Ipaddress.parse ("127.0.0.1");
Bind the acquired IP address and port number to a network node
IPEndPoint point = new IPEndPoint (address, 8098);
Try
{
The client socket is connected to the network node using connect
Socketclient. Connect (point);
This.btnSendMessage.Enabled = true;
This.btnSendMessage.Visible = true;
This.txtMessage.Visible = true;
}
catch (Exception)
{
Debug.WriteLine ("Connection failed \ r \ n");
This.txtDebugInfo.AppendText ("Connection failed \ r \ n");
Return
}
Threadclient = new Thread (recv);
Threadclient. IsBackground = true;
Threadclient. Start ();
}
How to receive information from the service side
void Recv ()
{
int x = 0;
Continuous monitoring of messages sent from the service side
while (true)
{
Try
{
Defines a 1M memory buffer for temporary storage of received messages
byte[] arrrecvmsg = new byte[1024 * 1024];
The data received by the client socket is stored in the memory buffer and gets the length
int length = Socketclient. Receive (ARRRECVMSG);
Converts the array of characters acquired by a socket into a string that can be understood by a person
String strrevmsg = Encoding.UTF8.GetString (arrrecvmsg, 0, length);
if (x = = 1)
{
This.txtDebugInfo.AppendText ("server:" + getcurrenttime () + "\ r \ n" + strrevmsg + "\r\n\n");
Debug.WriteLine ("server:" + getcurrenttime () + "\ r \ n" + strrevmsg + "\r\n\n");
}
Else
{
This.txtDebugInfo.AppendText (strrevmsg + "\r\n\n");
Debug.WriteLine (strrevmsg + "\r\n\n");
x = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine ("Remote server has disconnected" + "\r\n\n");
Debug.WriteLine ("Remote server has disconnected" + "\ r \ n");
Break
}
}
}
Get current system time
DateTime GetCurrentTime ()
{
DateTime currenttime = new DateTime ();
CurrentTime = DateTime.Now;
return currenttime;
}
Methods for sending character information to the server
void Clientsendmsg (String sendmsg)
{
Converts the input content string to a machine-recognized byte array
byte[] arrclientsendmsg = Encoding.UTF8.GetBytes (sendmsg);
Calling a client socket to send a byte array
Socketclient. Send (ARRCLIENTSENDMSG);
Append the sent information to the Chat content text box
Debug.WriteLine ("Hello ...." + ":" + getcurrenttime () + "\ r \ n" + sendmsg + "\r\n\n");
This.txtDebugInfo.AppendText ("Hello ...." + ":" + getcurrenttime () + "\ r \ n" + sendmsg + "\r\n\n");
}
private void Btnsendmessage_click_1 (object sender, EventArgs e)
{
Call the Clientsendmsg method to send the information entered in the text box to the server
Clientsendmsg (This.txtMessage.Text.Trim ());
This.txtMessage.Clear ();
}
}
}
Server
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Net.Sockets;
Using System.Net;
Using System.Threading;
Namespace Csocket
{
public class Program
{
Create a socket that communicates with the client
static Socket socketwatch = null;
Defines a collection that stores client information
Static dictionary<string, socket> clientconnectionitems = new dictionary<string, socket> {};
public static void Main (string[] args)
{
Defines a socket to listen for messages sent by the client, including three parameters (IP4 addressing protocol, streaming connection, TCP protocol)
Socketwatch = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);
Server sends information requires an IP address and port number
IPAddress address = Ipaddress.parse ("127.0.0.1");
Bind IP address and port number to network node point
IPEndPoint point = new IPEndPoint (address, 8098);
This port is specifically designed to monitor the
Listening for bound network nodes
Socketwatch. Bind (point);
Limit the listening queue length of the socket to 20
Socketwatch. Listen (20);
Thread responsible for listening to the client: Creating a listener thread
Thread threadwatch = new Thread (watchconnecting);
Set the form thread to synchronize with the background and end with the end of the main thread
Threadwatch. IsBackground = true;
Start thread
Threadwatch. Start ();
Console.WriteLine ("Turn on monitoring ... ");
Console.WriteLine ("Click Enter any data to exit the program ... ");
Console.readkey ();
Console.WriteLine ("Exit the Listener and close the program.") ");
}
Listening for requests from clients
static void Watchconnecting ()
{
Socket connection = null;
Constantly listening to requests from clients
while (true)
{
Try
{
Connection = Socketwatch. Accept ();
}
catch (Exception ex)
{
Hint Socket listener exception
Console.WriteLine (ex. Message);
Break
}
Get the IP and port number of the client
IPAddress ClientIP = (connection. Remoteendpoint as IPEndPoint). Address;
int clientport = (connection. Remoteendpoint as IPEndPoint). Port;
Let the customer display "connected successfully" information
String sendmsg = "Connection server succeeded!" \ r \ n "+" Local IP: "+ clientip +", local port "+ clientport.tostring ();
byte[] arrsendmsg = Encoding.UTF8.GetBytes (sendmsg);
Connection. Send (ARRSENDMSG);
Client Network Node number
String remoteendpoint = connection. Remoteendpoint.tostring ();
Show connection to Client
Console.WriteLine ("Success with" + Remoteendpoint + "Client Establish connection! \t\n ");
Adding Client Information
Clientconnectionitems.add (remoteendpoint, connection);
IPEndPoint netpoint = new IPEndPoint (clientip,clientport);
IPEndPoint Netpoint = connection. Remoteendpoint as IPEndPoint;
Create a communication thread
Parameterizedthreadstart pts = new Parameterizedthreadstart (recv);
Thread thread = new Thread (pts);
Set as a background thread and exit with the main thread exiting
Thread. IsBackground = true;
Start thread
Thread. Start (connection);
}
}
<summary>
Receive client-sent information from client socket object
</summary>
<param name= "Socketclientpara" ></param>
static void Recv (object Socketclientpara)
{
Socket socketserver = Socketclientpara as socket;
while (true)
{
Creates a memory buffer with a size of 1024*1024 bytes or 1M
byte[] arrserverrecmsg = new byte[1024 * 1024];
Deposits the received information into the memory buffer and returns the length of its byte array
Try
{
int length = socketserver.receive (arrserverrecmsg);
Converts a machine-accepted byte array into a string that can be read by a human
String strsrecmsg = Encoding.UTF8.GetString (arrserverrecmsg, 0, length);
Attaches the sent string information to the text box txtmsg
Console.WriteLine ("Client:" + Socketserver.remoteendpoint + ", Time:" + getcurrenttime () + "\ r \ n" + strsrecmsg + "\r\n\n");
Socketserver.send (Encoding.UTF8.GetBytes ("test server can send data to client"));
}
catch (Exception ex)
{
Clientconnectionitems.remove (SocketServer.RemoteEndPoint.ToString ());
Console.WriteLine ("Client Count:" + clientconnectionitems.count);
Hint Socket listener exception
Console.WriteLine ("Client" + Socketserver.remoteendpoint + "disconnected" + "\ r \ n" + ex.) Message + "\ r \ n" + ex. StackTrace + "\ r \ n");
Close the socket that was previously received and communicated to the client
Socketserver.close ();
Break
}
}
}
Static DateTime GetCurrentTime ()
{
DateTime currenttime = new DateTime ();
CurrentTime = DateTime.Now;
return currenttime;
}
}
}
C # Socket Communication