C#的网口通信
一、
命令行 客户端程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace client
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("192.168.8.100");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8888)); //配置服务器IP与端口
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
return;
}
//通过 clientSocket 发送数据
for (int i = 0; i < 10; i++)
{
try
{
Thread.Sleep(1000); //等待1秒钟
string sendMessage = "client send Message Hellp" + DateTime.Now;
clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("向服务器发送消息:{0}" + sendMessage);
//通过clientSocket接收数据
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("接收服务器消息:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
Console.WriteLine("发送完毕,按回车键退出");
Console.ReadLine();
}
}
}
命令行 服务器端程序:
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 8888; //端口
static Socket serverSocket;
static Socket clientSocket;
static void Main(string[] args)
{
//服务器IP地址
IPAddress ip = IPAddress.Parse("192.168.8.100");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口
serverSocket.Listen(10); //设定最多10个排队连接请求
Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
//通过Clientsoket发送数据
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
///
/// 监听客户端连接
///
private static void ListenClientConnect()
{
while (true)
{
clientSocket = serverSocket.Accept();
// clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
///
/// 接收消息
///
///
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//通过clientSocket接收数据
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
myClientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
服务器 客户端发送、接收线程优化
服务器端程序:
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;
namespace Serverl //ConsoleApplication1
{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 8888; //端口
static Socket serverSocket;
static Socket clientSocket;
static void Main(string[] args)
{
//服务器IP地址
IPAddress ip = IPAddress.Parse("192.168.8.100");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口
serverSocket.Listen(10); //设定最多10个排队连接请求
Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
//通过Clientsoket发送数据
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
///
/// 监听客户端连接
///
private static void ListenClientConnect()
{
while (true)
{
clientSocket = serverSocket.Accept();
// clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket); // 线程间传参
}
}
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//通过clientSocket接收数据
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
// myClientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
客户端程序:(同步接收模式)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace client
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("192.168.8.100");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8888)); //配置服务器IP与端口
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
return;
}
Thread socket_send = new Thread(socket_send_callback);
socket_send.Start(clientSocket);
Thread socket_receive = new Thread(socket_receive_callback);
socket_receive.Start(clientSocket);
}
static void socket_send_callback(object clientSocket)
{
Socket client_socket = (Socket)clientSocket ;
try
{
while (true)
{
Thread.Sleep(1000); //等待1秒钟
string sendMessage = "client send Message Hellp" + DateTime.Now;
client_socket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("向服务器发送消息:{0}" + sendMessage);
}
}
catch
{
client_socket.Shutdown(SocketShutdown.Both);
client_socket.Close();
}
}
//通过 clientSocket 发送数据
static void socket_receive_callback(object clientSocket)
{
Socket client_socket = (Socket)clientSocket;
int receiveLength = client_socket.Receive(result);//通过clientSocket接收数据
Console.WriteLine("接收服务器消息:{0}", result);
}
}
}
客户端异步接收模式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace client
{
class Program
{
private static byte[] result = new byte[1024];
static byte[] receive_buffer = new byte[1024];
static void Main(string[] args)
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("192.168.8.100");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8888)); //配置服务器IP与端口
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
return;
}
Thread socket_send = new Thread(socket_send_callback);
socket_send.Start(clientSocket);
Thread socket_receive = new Thread(socket_receive_callback);
socket_receive.Start(clientSocket);
}
static void socket_send_callback(object clientSocket)
{
Socket client_socket = (Socket)clientSocket ;
try
{
while (true)
{
Thread.Sleep(1000); //等待1秒钟
string sendMessage = "client send Message Hellp" + DateTime.Now;
client_socket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("向服务器发送消息:{0}" + sendMessage);
}
}
catch
{
client_socket.Shutdown(SocketShutdown.Both);
client_socket.Close();
}
}
//通过 clientSocket 发送数据
static void socket_receive_callback(object clientSocket)
{
Socket client_socket = (Socket)clientSocket;
// 异步接收
client_socket.BeginReceive(receive_buffer, 0, receive_buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), client_socket);
}
static void ReceiveCallback(IAsyncResult result)
{
Socket ts = (Socket)result.AsyncState;
ts.EndReceive(result);
result.AsyncWaitHandle.Close();
Console.WriteLine("收到消息:{0}", Encoding.ASCII.GetString(receive_buffer));
//清空数据,重新开始异步接收
receive_buffer = new byte[receive_buffer.Length];
ts.BeginReceive(receive_buffer, 0, receive_buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ts);
}
}
}
觉得有帮助,别忘了打赏下