Socket通信客户端和服务端代码

时间:2022-01-23 22:16:45

这两天研究了下Socket通信,简单实现的客户端和服务端代码

先上winfrom图片,客户端和服务端一样Socket通信客户端和服务端代码

 

服务端代码:

Socket通信客户端和服务端代码Socket通信客户端和服务端代码
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.Sockets;
using System.Net;

namespace Server
{
public partial class Form1 : Form
{
private List<Socket> listSocket = new List<Socket>();
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls
= false;
}

private void btnStart_Click(object sender, EventArgs e)
{
/*
* AddressFamily.InterNetwork:寻址方式
* SocketType.Stream:传输数据方式
* ProtocolType.Tcp:通信协议
*/
//1.创建一个socket对象
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

//2.创建一个IP地址
IPAddress address =IPAddress.Parse(txtIP.Text.Trim());

//3.创建一个EndPoint
IPEndPoint ipEndPoint = new IPEndPoint(address,int.Parse(txtPort.Text));

//4.绑定一个端口:独享此端口
socket.Bind(ipEndPoint);

//5.开启监听
socket.Listen(10);

AddShow(
"服务器启动,开始监听。。。");
//6.开始接受客户端的连接
//此代码一执行就阻塞当前线程,等待客户端的连接
Task task = Task.Factory.StartNew(x => {
Socket serverSocket
= x as Socket;
while (true)
{
//客户端一连接上之后,服务器端自动生产一个跟客户端通信的socket
Socket workSocket = serverSocket.Accept();
AddShow(
"有一个连接上"+workSocket.RemoteEndPoint.ToString());
workSocket.Send(Encoding.Default.GetBytes(
"你好"));

listSocket.Add(workSocket);

//接收消息
Task t = Task.Factory.StartNew(c => {
Socket recSocket
= c as Socket;
while (true)
{
try
{
byte[] bufferData = new byte[1024 * 1024];
int length = recSocket.Receive(bufferData);
if (length <= 0)
{
AddShow(recSocket.RemoteEndPoint.ToString()
+ "正常退出");
listSocket.Remove(recSocket);
//客户端退出会发送一个空字节过来
recSocket.Shutdown(SocketShutdown.Both);
recSocket.Close();

return;
}
string recStr = Encoding.Default.GetString(bufferData, 0, length);
AddShow(recSocket.RemoteEndPoint.ToString());
AddShow(recStr);
}
catch (Exception ex)
{
//异常退出捕获
AddShow(recSocket.RemoteEndPoint.ToString() + "异常退出");
listSocket.Remove(recSocket);
//客户端退出会发送一个空字节过来
recSocket.Shutdown(SocketShutdown.Both);
recSocket.Close();

}
}
},workSocket);
}

},socket);

}

public void AddShow(string message)
{
//判断现在线程是否是创建txtShow的线程
if (txtShow.InvokeRequired)
{
//在拥有该线程的句柄上去执行
txtShow.Invoke(() =>
{
this.txtShow.Text += message + "\r\n";
});
}
else
{
this.txtShow.Text += message + "\r\n";
}
}

private void btnSend_Click(object sender, EventArgs e)
{
string str = txtMsg.Text.Trim();
byte[] data = Encoding.Default.GetBytes(str);
//群发消息
foreach (Socket item in listSocket)
{
item.Send(data);
}
}
}
}
View Code

客户端代码:

Socket通信客户端和服务端代码Socket通信客户端和服务端代码
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;

namespace Client
{
public partial class Form1 : Form
{
Socket connectSocket
= null;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls
= false;
}

private void btnStart_Click(object sender, EventArgs e)
{
//1.创建一个socket连接
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

//2.连接到客户端
socket.Connect(IPAddress.Parse(txtIP.Text.Trim()),int.Parse(txtPort.Text.Trim()));

AddShow(socket.RemoteEndPoint.ToString()
+"连接成功");
connectSocket
= socket;

//3.开启异步线程,不停接收消息
Task task = Task.Factory.StartNew(()=> {
while (true)
{
try
{
byte[] bufferData = new byte[1024 * 1024];
int length = connectSocket.Receive(bufferData);
if (length<=0)
{
//服务器退出,发送空消息
AddShow("连接正常退出");
connectSocket.Shutdown(SocketShutdown.Both);
connectSocket.Close();
return;
}
string str = Encoding.Default.GetString(bufferData, 0, length);
AddShow(connectSocket.RemoteEndPoint.ToString());
AddShow(str);
}
catch (Exception ex)
{
AddShow(
"连接异常退出");
if (connectSocket!=null&&connectSocket.Connected)
{
connectSocket.Shutdown(SocketShutdown.Both);
connectSocket.Close();
}
return;
}
}

});
}

public void AddShow(string message)
{
if (txtShow.InvokeRequired)
{
txtShow.Invoke(()
=> {
this.txtShow.Text += message + "\r\n";
});
}
else
{
this.txtShow.Text += message + "\r\n";
}

}

private void btnSend_Click(object sender, EventArgs e)
{
byte[] data = Encoding.Default.GetBytes(txtMsg.Text.Trim());
connectSocket.Send(data);
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//关闭窗体同时关闭socket
if (connectSocket!=null&&connectSocket.Connected)
{
connectSocket.Shutdown(SocketShutdown.Both);
connectSocket.Close();
}
}
}
}
View Code