当前位置:网站首页>Tclistener server and tcpclient client use -- socket listening server and socketclient use
Tclistener server and tcpclient client use -- socket listening server and socketclient use
2022-06-30 09:25:00 【LongtengGensSupreme】
Tcplistener The service side and tcpclient Client side usage --Socket Monitoring server and Socketclient Client side usage
public static void Start()
{
// Turn on httplistener Listener Service
//Thread thread = new Thread(new ThreadStart(StartTcpListening))
//{
// IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
//};
//thread.Start();
// Turn on Socket Listener Service
Thread thread = new Thread(new ThreadStart(StartSocketListening))
{
IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
};
thread.Start();
// test
//Thread threadClient = new Thread(new ThreadStart(TestTCPClient))
//{
// IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
//};
//threadClient.Start();
}
/// <summary>
/// Turn on httplistener Listener Service
/// </summary>
public static void StartTcpListening()
{
TcpListener tcpListener = null;
#region TcpListener Server side
try
{
while (true)
{
try
{
tcpListener = new TcpListener(IPAddress.Any, 5566);
tcpListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
tcpListener.Start();//tcpListener.Start(100);100 Is to set the maximum number of connected clients
}
catch (Exception e)
{
Thread.Sleep(1000);// Listening service startup failed , Pause 1 Seconds before starting the listening service
}
try
{
while (true)
{
//try
//{
// Get connected clients
TcpClient client = tcpListener.AcceptTcpClient();//Socket socket = tcpListener.AcceptSocket();
client.LingerState.Enabled = false;
string data = null;
byte[] bytes = new byte[1024];
NetworkStream stream = client.GetStream();
int i = stream.Read(bytes, 0, bytes.Length);
data = Encoding.Default.GetString(bytes, 0, i);
byte[] msg = Encoding.Default.GetBytes(data + "ok");
stream.Write(msg, 0, msg.Length);
stream.Flush();
#region Multiple real-time read and write information
//ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
//ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
//System.Diagnostics.Trace.WriteLine($" Worker threads maximum : {nWorkThreads}, You can use :{nWorkAvailable}---i/o Most threads : {nPortThreads}, You can use :{nPortAvailable}");
Thread thread = new Thread(ProcessTcpData)
{
IsBackground = true
};
thread.Start(client);
#endregion
#region Only single real-time read and write information
//NetworkStream stream = client.GetStream();
//int i;
//while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
//{
// data = Encoding.Default.GetString(bytes, 0, i);
// System.Diagnostics.Trace.WriteLine("tcpListener Received: {0}", data);
// //byte[] msg = Encoding.Default.GetBytes(data + "ok");
// //stream.Write(msg, 0, msg.Length);
// //System.Diagnostics.Trace.WriteLine("Sent: {0}", data);
// byte[] msg = Encoding.Default.GetBytes(data + "-------ok");
// stream.Write(msg, 0, msg.Length);
// System.Diagnostics.Trace.WriteLine("tcpListener Sent: {0}", data);
//}
#endregion
//client.Close(); No need to close
//}
//catch (Exception e)
//{
//}
}
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
#endregion
#region Listen for all of the local ip
//Socket socketServer = null;
//try
//{
// socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// socketServer.Bind(new IPEndPoint(IPAddress.Any, 7788));
// socketServer.Listen(10);
// //socketServer.LingerState.Enabled = false;
// while (true)
// {
// // closed
// var socket0 = socketServer.Accept();
// byte[] vs = new byte[1024];
// int count = socket0.Receive(vs);
// // Hair
// byte[] vs1 = new byte[1024];
// socket0.Send(vs1);
// }
//}
//catch (Exception)
//{
// throw;
//}
//finally
//{
// socketServer.Close();
// //socketServer.Shutdown(SocketShutdown.Both);
//}
#endregion
}
/// <summary>
/// tcplistener Data processing received by the server
/// </summary>
/// <param name="clientData"></param>
public static void ProcessTcpData(object clientData)
{
try
{
TcpClient client = clientData as TcpClient;
NetworkStream stream = client.GetStream();
string data = null;
byte[] bytes = new byte[1024];
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.Default.GetString(bytes, 0, i);
System.Diagnostics.Trace.WriteLine("tcpListener Received: {0}", data);
//byte[] msg = Encoding.Default.GetBytes(data + "ok");
//stream.Write(msg, 0, msg.Length);
//System.Diagnostics.Trace.WriteLine("Sent: {0}", data);
byte[] msg = Encoding.Default.GetBytes(data + "-------ok");
stream.Write(msg, 0, msg.Length);
System.Diagnostics.Trace.WriteLine("tcpListener Sent: {0}", data);
ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
System.Diagnostics.Trace.WriteLine($" Worker threads maximum : {nWorkThreads}, You can use :{nWorkAvailable}---i/o Most threads : {nPortThreads}, You can use :{nPortAvailable}");
}
}
catch (Exception e)
{
}
}
/// <summary>
/// test TCPClient
/// </summary>
public static void TestTCPClient()
{
TcpClient tcpClient = null;
try
{
//tcpClient = new TcpClient(new IPEndPoint(System.Net.Dns.Resolve(IPAddress.Any.ToString()).AddressList[0].Address, 7788));
tcpClient = new TcpClient();
tcpClient.Connect("127.0.0.1", 5566);
if (tcpClient.Connected)
{
String data = null;
int w = 0;
string senddata = null;
var stream = tcpClient.GetStream();
while (true)
{
// write in
senddata = $" Ha ha ha kkkk2233--{++w}";
#if DEBUG
Console.WriteLine($"TcpClient Send: {senddata}");
#else
System.Diagnostics.Trace.WriteLine($"TcpClient Send: {senddata}");
#endif
byte[] sendBytes = Encoding.ASCII.GetBytes(senddata);
stream.Write(sendBytes, 0, sendBytes.Length);
// read out
byte[] receBytes = new byte[1024];
var rece = stream.Read(receBytes, 0, receBytes.Length);
data = Encoding.ASCII.GetString(receBytes, 0, rece);
#if DEBUG
Console.WriteLine($"TcpClient Received: {data}");
#else
System.Diagnostics.Trace.WriteLine($"TcpClient Received: {data}");
#endif
ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
Console.WriteLine($" Worker threads maximum : {nWorkThreads}, You can use :{nWorkAvailable}---i/o Most threads : {nPortThreads}, You can use :{nPortAvailable}");
Thread.Sleep(2000);
}
}
}
catch (Exception e)
{
System.Diagnostics.Trace.WriteLine(" TcpClient Exception: {0}", e.InnerException.Message);
//throw;
}
finally
{
tcpClient.Close();
}
}
/// <summary>
/// Turn on Socket Listener Service
/// </summary>
public static void StartSocketListening()
{
Socket socketServer = null;
try
{
while (true)
{
try
{
socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketServer.Bind(new IPEndPoint(IPAddress.Any, 7788));
socketServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
//socketServer.LingerState.Enabled = false;
socketServer.Listen(100);//socketServer.Listen(100);100 Is to set the maximum number of connected clients
}
catch (Exception e)
{
Thread.Sleep(1000);// Listening service startup failed , Pause 1 Seconds before starting the listening service
}
try
{
while (true)
{
// Get connected clients
Socket socket = socketServer.Accept();
socket.LingerState.Enabled = false;
string data = null;
byte[] bytes = new byte[1024];
int i = socket.Receive(bytes);
data = Encoding.Default.GetString(bytes, 0, i);
byte[] arrSendMsg = Encoding.UTF8.GetBytes(data + "ok");
socket.Send(arrSendMsg);
#region Multiple real-time read and write information
//ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
//ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
//System.Diagnostics.Trace.WriteLine($" Worker threads maximum : {nWorkThreads}, You can use :{nWorkAvailable}---i/o Most threads : {nPortThreads}, You can use :{nPortAvailable}");
Thread thread = new Thread(ProcessSocketData)
{
IsBackground = true
};
thread.Start(socket);
#endregion
#region Only single real-time read and write information
//while (true)
//{
// // closed
// var socket0 = socketServer.Accept();
// byte[] vs = new byte[1024];
// int count = socket0.Receive(vs);
// // Hair
// byte[] vs1 = new byte[1024];
// socket0.Send(vs1);
//}
#endregion
}
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
}
/// <summary>
/// Socket Data processing received by the server
/// </summary>
/// <param name="clientData"></param>
public static void ProcessSocketData(object clientData)
{
try
{
Socket socketServer = clientData as Socket;
while (true)
{
try
{
byte[] serverRecMsg = new byte[1024];
int length = socketServer.Receive(serverRecMsg);
string strSRecMsg = Encoding.UTF8.GetString(serverRecMsg, 0, length);
socketServer.Send(Encoding.UTF8.GetBytes(strSRecMsg + "ok"));
//System.Diagnostics.Trace.WriteLine($"Socket Sent: {strSRecMsg}");
//ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
//ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
//System.Diagnostics.Trace.WriteLine($" Worker threads maximum : {nWorkThreads}, You can use :{nWorkAvailable}---i/o Most threads : {nPortThreads}, You can use :{nPortAvailable}");
serverRecMsg.DefaultIfEmpty();
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
}
/// <summary>
/// test Socketlient
/// </summary>
public static void TestSocketlient()
{
Socket socketClient = null;
try
{
//tcpClient = new TcpClient(new IPEndPoint(System.Net.Dns.Resolve(IPAddress.Any.ToString()).AddressList[0].Address, 7788));
socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//socketClient.Connect(new IPEndPoint(IPAddress.Any, 7788));
socketClient.Connect("127.0.0.1", 7788);
if (socketClient.Connected)
{
String data = null;
int w = 0;
string senddata = null;
while (true)
{
// write in
senddata = $" Ha ha ha kkkk2233--{++w}";
#if DEBUG
Console.WriteLine($"SocketClient Send: {senddata}");
#else
System.Diagnostics.Trace.WriteLine($"SocketClient Send: {senddata}");
#endif
byte[] sendBytes = Encoding.ASCII.GetBytes(senddata);
socketClient.Send(sendBytes);
// read out
byte[] receBytes = new byte[1024];
var rece = socketClient.Receive(receBytes);
data = Encoding.ASCII.GetString(receBytes, 0, rece);
#if DEBUG
Console.WriteLine($"SocketClient Received: {data}");
#else
System.Diagnostics.Trace.WriteLine($"SocketClient Received: {data}");
#endif
ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
Console.WriteLine($" Worker threads maximum : {nWorkThreads}, You can use :{nWorkAvailable}---i/o Most threads : {nPortThreads}, You can use :{nPortAvailable}");
Thread.Sleep(2000);
}
}
}
catch (Exception e)
{
System.Diagnostics.Trace.WriteLine(" TcpClient Exception: {0}", e.InnerException.Message);
//throw;
}
finally
{
socketClient.Shutdown(SocketShutdown.Both);
socketClient.Disconnect(true);
socketClient.Close();
}
}边栏推荐
- Do you want the dialog box that pops up from the click?
- Summary of Android knowledge points and common interview questions
- [wechat applet] realize applet pull-down refresh and pull-up loading
- Interpretation of source code demand:a rotation equivariant detector for aerial object detection
- Flink Exception -- No ExecutorFactory found to execute the application
- Unsupportedclassversionerror is reported when starting jar package. How to repair it
- Resnet50+fpn for mmdet line by line code interpretation
- Opencv learning notes -day13 pixel value statistics calculation of maximum and minimum values, average values and standard deviations (use of minmaxloc() and meanstddev() functions)
- I'm late for school
- Icon resources
猜你喜欢

Guilin robust medical acquired 100% equity of Guilin Latex to fill the blank of latex product line

Dart asynchronous task

将线程绑定在某个具体的CPU逻辑内核上运行

Maxiouassigner of mmdet line by line interpretation

Opencv learning notes-day5 (arithmetic operation of image pixels, add() addition function, subtract() subtraction function, divide() division function, multiply() multiplication function

Solution to the eighth training competition of 2020 Provincial Games

Opencv learning notes -day 12 (ROI region extraction and inrange() function operation)

I'm late for school

Agp7.0|kts makes a reinforced plug-in

Talk about the kotlin cooperation process and the difference between job and supervisorjob
随机推荐
Rew acoustic test (IV): test principle of rew
Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)
Tutorial for beginners of small programs day01
Mmdet line by line code interpretation of positive and negative sample sampler
Get to know handler again
Common query and aggregation of ES
Opencv learning notes-day9 opencv's own color table operation (colormap coloraptypes enumeration data types and applycolormap() pseudo color function)
Invalid update: invalid number of sections. The number of sections contained in the table view after
Interpretation of source code demand:a rotation equivariant detector for aerial object detection
Esp32 things (VIII): music playing function of function development
Application of hongruan face recognition
12. problem set: process, thread and JNI architecture
Use Huawei performance management service to configure the sampling rate on demand
Anchorgenerator for mmdet line by line interpretation
Niuke walks on the tree (ingenious application of parallel search)
Talking about the difference between kotlin collaboration and thread
Metasploit practice - SSH brute force cracking process
Code management related issues
Do you want the dialog box that pops up from the click?
C # get the current timestamp