You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

226 lines
6.5 KiB

1 year ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data;
using System.Drawing;
namespace formula_manage.UserClass
{
public class TCPServer
{
//第一步:调用socket()函数创建一个用于通信的套接字
public static Socket listenSocket;
//字典集合:存储IP和Socket的集合
public static Dictionary<string, Socket> OnLineList = new Dictionary<string, Socket>();
//当前时间
private string CurrentTime
{
get { return DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine; }
}
//编码格式
Encoding econding = Encoding.Default;
public static void Start()
{
//第一步:调用socket()函数创建一个用于通信的套接字
listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//第二步:给已经创建的套接字绑定一个端口号,这一般通过设置网络套接口地址和调用Bind()函数来实现
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse("11080"));
try
{
listenSocket.Bind(endPoint);
}
catch (Exception ex)
{
MessageBox.Show("服务器开启失败:" + ex.Message, "开启服务器");
return;
}
//第三步:调用listen()函数使套接字成为一个监听套接字
listenSocket.Listen(10);
//ShowMessage("服务器开启成功");
MessageBox.Show("服务器开启成功");
//开启一个线程监听
Task.Run(new Action(() =>
{
ListenConnection();
}
));
}
public static void ListenConnection()
{
while (true)
{
Socket clientSocket = listenSocket.Accept();
string ip = clientSocket.RemoteEndPoint.ToString();
//更新在线列表
// AddOnLine(ip, true);
//更新在线列表集合
OnLineList.Add(ip, clientSocket);
// ShowMessage(ip + "上线了");
Task.Run(() => ReceiveMsg(clientSocket));
}
}
/// <summary>
/// 接收方法
/// </summary>
/// <param name="clientSocket"></param>
public static void ReceiveMsg(Socket clientSocket)
{
while (true)
{
//定义一个2M的缓冲区
byte[] buffer = new byte[1024 * 1024 * 2];
int length = -1;
try
{
length = clientSocket.Receive(buffer);
}
catch (Exception)
{
//客户端下线了
//更新在线列表
string ip = clientSocket.RemoteEndPoint.ToString();
// AddOnLine(ip, false);
OnLineList.Remove(ip);
break;
}
if (length == 0)
{
//客户端下线了
//更新在线列表
string ip = clientSocket.RemoteEndPoint.ToString();
// AddOnLine(ip, false);
OnLineList.Remove(ip);
break;
}
// if (length > 0)
// {
// string info = econding.GetString(buffer, 0, length);
// ShowMessage(info);
// }
}
}
/*
/// <summary>
/// 在线列表更新
/// </summary>
/// <param name="clientIp"></param>
/// <param name="value"></param>
private void AddOnLine(string clientIp, bool value)
{
Invoke(new Action(() =>
{
if (value)
{
this.lst_Online.Items.Add(clientIp);
}
else
{
this.lst_Online.Items.Remove(clientIp);
}
}));
}
/// <summary>
/// 更新接收区
/// </summary>
/// <param name="info"></param>
private void ShowMessage(string info)
{
Invoke(new Action(() =>
{
this.txt_Rcv.AppendText(CurrentTime + info + Environment.NewLine);
}));
}
*/
/*
/// <summary>
/// 消息发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Send_Click(object sender, EventArgs e)
{
if (this.lst_Online.SelectedItem != null)
{
foreach (string item in this.lst_Online.SelectedItems)
{
if (OnLineList.ContainsKey(item))
{
OnLineList[item].Send(econding.GetBytes(this.txt_Send.Text.Trim()));
}
}
}
else
{
MessageBox.Show("请先选择要发送的对象", "发送消息");
}
}
/// <summary>
/// 群发功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_SendAll_Click(object sender, EventArgs e)
{
foreach (string item in this.lst_Online.Items)
{
if (OnLineList.ContainsKey(item))
{
OnLineList[item].Send(econding.GetBytes(this.txt_Send.Text.Trim()));
}
}
}*/
}
}