1.最直白的Socket代码
服务端
// 创建一个用于监听的Socket
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定IP地址和端口号
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 12345);
listener.Bind(localEndPoint);
// 开始监听
Console.WriteLine("Waiting for a connection...");
listener.Listen(10);
while (true)
{
// 接受连接
Socket handler = listener.Accept();
Console.WriteLine($"Connected: {handler.RemoteEndPoint}");
// 读取数据
byte[] buffer = new byte[1024];
int bytesRec = handler.Receive(buffer);
string data = Encoding.ASCII.GetString(buffer, 0, bytesRec);
Console.WriteLine($"Received: {data}");
// 发送数据
byte[] msg = Encoding.ASCII.GetBytes("Hello from server!");
handler.Send(msg);
// 关闭连接
handler.Shutdown(SocketShutdown.Both);
handler.Close();
客户端
// 创建一个Socket并连接到服务器
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 12345);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remoteEP);
// 发送数据
string message = "Hello from client!";
byte[] msg = Encoding.ASCII.GetBytes(message);
int bytesSent = sender.Send(msg);
Console.WriteLine($"Sent: {message}");
// 接受数据
byte[] buffer = new byte[1024];
int bytesRec = sender.Receive(buffer);
string data = Encoding.ASCII.GetString(buffer, 0, bytesRec);
Console.WriteLine($"Received: {data}");
// 关闭连接
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadKey();
2.封装过有点绕的Socket代码
服务端
/// <summary>
/// 开始监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStartListen_Click(object sender, EventArgs e)
{
// 创建监听Socket
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// IP
IPAddress ip = IPAddress.Parse(this.tbIP.Text.Trim());
// 端口号
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.tbPort.Text.Trim()));
// 绑定IP地址和端口
socketWatch.Bind(point);
this.tbLog.AppendText("监听成功" + "\r\n");
// 设置最大连接数
socketWatch.Listen(10);
// 回调实例化
setTextValueCallBack = new SetTextValueCallBack(SetTextValue);
receiveMsgCallBack = new ReceiveMsgCallBack(ReceiveMsg);
setCmbCallBack = new SetCmbCallBack(AddCmbItem);
sendFileCallBack = new SendFileCallBack(SendFile);
// 线程开启监听
acceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen));
acceptSocketThread.IsBackground = true;
acceptSocketThread.Start(socketWatch);
}
/// <summary>
/// 监听
/// </summary>
/// <param name="obj"></param>
private void StartListen(object obj)
{
Socket sw = obj as Socket;
while (true)
{
// 等待连接
socketSend = socketWatch.Accept();
// 获取连接主机IP和端口
string rip = socketSend.RemoteEndPoint.ToString();
dicSocket.Add(rip, socketSend);
this.cmbIPList.Invoke(setCmbCallBack, rip);
string strMsg = "远程主机:" + socketSend.RemoteEndPoint + "连接成功";
// 回显
tbLog.Invoke(setTextValueCallBack, strMsg);
// 接收客户端消息线程
Thread threadReceive = new Thread(new ParameterizedThreadStart(Receive));
threadReceive.IsBackground = true;
threadReceive.Start(socketSend);
}
}
/// <summary>
/// 接收
/// </summary>
/// <param name="obj"></param>
private void Receive(object obj)
{
Socket socketR = obj as Socket;
socketR.ReceiveTimeout = 5000;
try
{
if (socketR == null || !socketR.Connected)
{
SetTextValue("客户端关闭连接...");
return;
}
while (true)
{
// 接收到的消息缓存区
byte[] buffer = new byte[2048];
// 接收到的有效字节数
int count = socketR.Receive(buffer); // 阻塞操作
if (count == 0)
{
// 客户端关闭
return;
}
// 回显接收到的消息
string str = Encoding.Default.GetString(buffer, 0, count);
string strR = "接收:" + socketR.RemoteEndPoint + " 发送的消息:" + str;
tbLog.Invoke(receiveMsgCallBack, strR);
}
}
catch (SocketException sex)
{
tbLog.Invoke(receiveMsgCallBack, "网络异常:" + "[" + socketR.RemoteEndPoint.ToString() + "]" + sex.Message);
dicSocket.Remove(socketR.RemoteEndPoint.ToString());
}
catch (ObjectDisposedException dex)
{
tbLog.Invoke(receiveMsgCallBack, "连接异常:" + "[" + socketR.RemoteEndPoint.ToString() + "]" + dex.Message);
}
catch (Exception ex)
{
tbLog.Invoke(receiveMsgCallBack, "接收客户端消息异常:" + ex.Message);
}
}
客户端文章来源:https://www.toymoban.com/news/detail-597036.html
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(this.tbIP.Text.Trim());
socketSend.Connect(ip, Convert.ToInt32(this.tbPort.Text.Trim()));
// 实例化
setTextCallBack = new SetTextCallBack(SetValue);
receiveMsgCallBack = new ReceiveMsgCallBack(SetValue);
// 线程接收服务端消息
threadReceive = new Thread(new ThreadStart(Receive));
threadReceive.IsBackground = true;
threadReceive.Start();
SetValue("连接成功...");
}
catch (Exception ex)
{
MessageBox.Show("连接服务端出错:" + ex.Message);
}
}
/// <summary>
/// 接收服务器消息
/// </summary>
private void Receive()
{
try
{
if (socketSend == null || !socketSend.Connected)
{
SetValue("连接被关闭...");
return;
}
while (true)
{
byte[] buffer = new byte[2048];
// 接收的字节
int r = socketSend.Receive(buffer); // 阻塞操作
if (r == 0)
{
return;
}
// 判断发送的数据类型
// 文字消息
if (buffer[0] == 0)
{
string str = Encoding.Default.GetString(buffer, 1, r - 1);
this.tbLog.Invoke(receiveMsgCallBack, "接收服务端:" + socketSend.RemoteEndPoint + " 发送消息:" + str);
}
// 文件消息
if (buffer[0] == 1)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = @"";
sfd.Title = "请选择要保存的文件";
sfd.Filter = "所有文件|*.*";
sfd.ShowDialog(this);
string strPath = sfd.FileName;
using (FileStream fsWrite = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write))
{
fsWrite.Write(buffer, 1, r - 1);
}
MessageBox.Show("保存文件成功");
}
}
}
catch (SocketException sex)
{
MessageBox.Show("网络异常:" + sex.Message);
}
catch (Exception ex)
{
MessageBox.Show("接收服务端消息异常:" + ex.Message);
}
}
3.GitHub代码
https://github.com/harrylsp/AndroidADBDriver文章来源地址https://www.toymoban.com/news/detail-597036.html
到了这里,关于C# Socket编程(服务端、客户端)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!