using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class MainFrm : Form
{
List<Socket> ClientProxSocketList = new List<Socket>();
public MainFrm()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
/// <summary>
/// 启动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//创建Socket
Socket socket =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定端口IP
socket.Bind(new IPEndPoint(IPAddress.Parse(txtIP.Text),int.Parse(txtPort.Text)));
//开启监听
socket.Listen(10);//最大监听
//开启客户端链接
ThreadPool.QueueUserWorkItem(new WaitCallback(AcceptClientConnect),socket);//将socket传给AcceptClientConnect做形参
}
/// <summary>
/// 接收服务连接
/// </summary>
/// <param name="socket"></param>
private void AcceptClientConnect(object socket)
{
var serverSocket=socket as Socket;//将形参转换为Socket形式
AppendTextToTxtLog("服务器开始接收客户端链接.");
while (true)
{
var proxSocket=serverSocket.Accept();//创建Socket连接,并返回一个Socket对象
AppendTextToTxtLog(string.Format("客户端:{0}连接上了",proxSocket.RemoteEndPoint.ToString()));
ClientProxSocketList.Add(proxSocket);
//不断接收客户端发来的消息
ThreadPool.QueueUserWorkItem(ReceiveData,proxSocket);
}
}
/// <summary>
/// 接收客户端消息
/// </summary>
/// <param name="socket"></param>
public void ReceiveData(object socket)
{
var proxSocket=socket as Socket;
byte[] data=new byte[1024*1024];
while (true)
{
int len= 0;
try
{
len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);//从proxSocket的Socket接收数据,并将其存储在名为data的字节数组中,然后使用接收到的字节数更新len变量
}
catch (Exception ex)
{
//异常退出
AppendTextToTxtLog(string.Format("客户端{0}:非正常退出", proxSocket.RemoteEndPoint.ToString()));
ClientProxSocketList.Remove(proxSocket);
return;
}
if (len <= 0)
{
//客户端正常退出
AppendTextToTxtLog(string.Format("客户端{0}:正常退出", proxSocket.RemoteEndPoint.ToString()));
ClientProxSocketList.Remove(proxSocket);
return;
}
//把接收的数据放文本框上面
string str=Encoding.Default.GetString(data,0,len);
AppendTextToTxtLog(string.Format("接收客户端:{0}的消息是:{1}",proxSocket.RemoteEndPoint.ToString(),str));
}
}
/// <summary>
/// 往日志的文本框上追加数据
/// </summary>
/// <param name="txt"></param>
public void AppendTextToTxtLog(string txt)
{
if (txtLog.InvokeRequired)//判断是否跨线程
{
txtLog.Invoke(new Action<string>
(s => { this.txtLog.Text = string.Format("{0}\r\n{1}", s, txtLog.Text); })
, txt);
}
else
{
this.txtLog.Text = string.Format(txt);
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendMsg_Click(object sender, EventArgs e)
{
foreach (var proxSocket in ClientProxSocketList)
{
if (proxSocket.Connected)
{
byte[] data=Encoding.Default.GetBytes(txtMsg.Text);
proxSocket.Send(data, 0, data.Length, SocketFlags.None);
}
}
}
private void txtIP_TextChanged(object sender, EventArgs e)
{
}
private void MainFrm_Load(object sender, EventArgs e)
{
}
private void btnSendShake_Click(object sender, EventArgs e)
{
foreach (var proxSocket in ClientProxSocketList)
{
if (proxSocket.Connected)
{
proxSocket.Send(new byte[] {2},SocketFlags.None);
}
}
}
/// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())//释放文件
{
if (ofd.ShowDialog() != DialogResult.OK)// 如果没有显示文件选择对话框
{
return;
}
byte[] data=File.ReadAllBytes(ofd.FileName);
byte[] result=new byte[data.Length+1];
result[0] = 3;
Buffer.BlockCopy(data,0,result,1,data.Length);
foreach (var proxSocket in ClientProxSocketList)
{
if (!proxSocket.Connected)
{
continue;
}
proxSocket.Send(result, SocketFlags.None);
}
}
}
}
}
Socket服务端
于 2024-01-12 13:53:46 首次发布