C# Winform Soket 网络编程 多个客户端连接服务器并返回客户端操作请求

时间:2021-04-30 06:32:51

2017.8.2

服务器:

 #region 参数与集合
/// <summary>
/// 客户端IP
/// </summary>
string clientIP;
/// <summary>
/// IP地址(IPAddress)
/// </summary>
string thisIp;
/// <summary>
/// 端口(Port)
/// </summary>
int port;
/// <summary>
/// Thread:监听客户端连接请求
/// </summary>
Thread watchClientThread = null;
/// <summary>
/// Socket:监听客户端连接请求
/// </summary>
Socket watchClientSocker = null;
/// <summary>
/// 套接字集合(Socket Gether)
/// </summary>
Dictionary<string, Socket> dictSocket = new Dictionary<string, Socket>();
/// <summary>
/// 线程集合(Thread Gether)
/// </summary>
Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();
#endregion #region 获取本地IP地址
/// <summary>
/// 获取本地IP地址
/// </summary>
private void GetIPAddress()
{
NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces();
if (nis.Length > )
{
for (int i = ; i < nis.Length; i++)
{
foreach (var item in nis[i].GetIPProperties().UnicastAddresses)
{
string s = item.Address.ToString();
string[] ss = s.Split('.');
if (ss.Length == )
{
if (ss[].ToString() != "" && ss[].ToString() == "")
{
thisIp = s;
break;
}
}
}
}
}
}
#endregion #region 启动服务器
/// <summary>
/// 启动服务器
/// </summary>
public void SocketStart()
{
GetIPAddress();
port = ;
watchClientSocker = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(thisIp), port);
try
{
watchClientSocker.Bind(endPoint);
}
catch (SocketException se)
{
rtbMonitoring.Text += "异常:" + se.Message + "\n";
return;
}
catch (Exception ex)
{
rtbMonitoring.Text += "异常:" + ex.Message + "\n";
}
watchClientSocker.Listen();
watchClientThread = new Thread(WatchConnection);
watchClientThread.IsBackground = true;
watchClientThread.Start();
}
#endregion #region 开始监听客户端连接请求
/// <summary>
/// 开始监听客户端连接请求
/// </summary>
void WatchConnection()
{
while (true)
{
Socket socketConn = watchClientSocker.Accept();
clientIP = socketConn.RemoteEndPoint.ToString();
dictSocket.Add(clientIP, socketConn);
Thread thr = new Thread(ReccptionData);
thr.IsBackground = true;
thr.Start(socketConn);
dictThread.Add(clientIP, thr);
rtbMonitoring.Text += clientIP + " 连接成功" + "\n";
}
}
#endregion #region 客户端信息处理
/// <summary>
/// 客户端信息处理
/// </summary>
/// <param name="socketConn"></param>
void ReccptionData(object socketConn)
{
Socket socketClient = socketConn as Socket;
while (true)
{
byte[] arrRec = new byte[ * * ];
int length = -;
try
{
length = socketClient.Receive(arrRec);
}
catch (SocketException se)
{
rtbMonitoring.Text += "异常:" + se.Message+"\n";
dictSocket.Remove(socketClient.RemoteEndPoint.ToString());
dictThread.Remove(socketClient.RemoteEndPoint.ToString());
break;
}
if (arrRec[] == )
{
clientIP = socketClient.RemoteEndPoint.ToString();
string strMsg = System.Text.Encoding.UTF8.GetString(arrRec, , length - );// 将接受到的字节数据转化成字符串;
ReturnData(strMsg);
rtbMonitoring.Text +=clientIP+":"+ strMsg + "\n";
}
if (arrRec[] == )
{
if (!Directory.Exists("FileInfo"))
{
Directory.CreateDirectory("FileInfo");
}
if (!File.Exists(arrRec + ".txt"))
{
File.Create(arrRec + ".txt");
}
string fileSavePath = arrRec + " .txt";
using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
{
fs.Write(arrRec, , length - );
rtbMonitoring.Text += "文件保存成功:" + fileSavePath + "\n"; }
}
} }
#endregion #region 返回请求数据
/// <summary>
/// 返回请求数据
/// </summary>
/// <param name="data"></param>
void ReturnData(string data)
{
string connectSql = "server=.;database=Thread_SocketDB;uid=sa;pwd=sa;";
string strMsg;
UserInfo u = new UserInfo();
GetSql getsql = new GetSql();
List<UserInfo> us = new List<UserInfo>();
string[] datas = data.Split('/');
string operationType = "";
string type = "";
string userName = "";
string pwd = "";
if (datas.Length > )
{
operationType = datas[];
type = datas[];
userName = datas[];
pwd = datas[];
}
switch (operationType)
{
case "用户":
switch (type)
{
case "登录":
SqlConnection con = new SqlConnection(connectSql);
con.Open();
SqlCommand com = new SqlCommand(getsql.GetSelectAll(), con);
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
u = new UserInfo();
u.UserName = dr["UserName"].ToString();
u.Pwd = dr["Pwd"].ToString();
us.Add(u);
}
dr.Close();
con.Close();
strMsg = "正在验证登录信息...";
SendContent(strMsg);
List<UserInfo> loginInfo = us.FindAll((p) =>
p.UserName == userName);
if (loginInfo.Count <= )
{
strMsg = "对不起,你的账号不存在!";
SendContent(strMsg); }
else
{
foreach (UserInfo userInfo in loginInfo)
{
u = userInfo;
} if (pwd != u.Pwd)
{ strMsg = "对不起,你的密码不正确!";
SendContent(strMsg); }
else
{
strMsg = "登录成功!";
SendContent(strMsg);
}
}
break;
case "编号查询": break;
}
break;
case "管理员": break;
}
}
#endregion #region 封装发送信息
/// <summary>
/// 封装发送信息
/// </summary>
/// <param name="strMsg"></param>
private void SendContent(string s)
{
byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(s);
byte[] arrSendMsg = new byte[arrMsg.Length + ];
arrSendMsg[] = ; // 用来表示发送的是消息数据
Buffer.BlockCopy(arrMsg, , arrSendMsg, , arrMsg.Length);
dictSocket[clientIP].Send(arrSendMsg);
}
#endregion

客户端:

  /// <summary>
/// 客户端套接字对象
/// </summary>
Socket sockClient = null;
/// <summary>
/// 客户端线程
/// </summary>
Thread threadCilent = null;
#region 开始连接字符串
/// <summary>
/// 开始连接字符串
/// </summary>
public void ServerConnect()
{
try
{
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.4.186"), );
sockClient = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
try
{
lbReception.Text = "正在与服务器进行连接...\n";
sockClient.Connect(endPoint);
}
catch (SocketException se)
{
lbReception.Text = "异常:" + se.Message + "\n";
return;
}
lbReception.Text = "连接成功!";
threadCilent = new Thread(Res);
threadCilent.IsBackground = true;
threadCilent.Start(); }
catch (Exception)
{
lbReception.Text = "IP无效!";
throw;
} } #region 接收数据处理
/// <summary>
/// 接收数据处理
/// </summary>
private void Res()
{ while (true)
{
// 定义一个2M的缓存区;
byte[] arrMsgRec = new byte[ * * ];
// 将接受到的数据存入到输入 arrMsgRec中;
int length = -;
try
{
length = sockClient.Receive(arrMsgRec); // 接收数据,并返回数据的长度;
}
catch (SocketException se)
{
lbReception.Text = "异常;" + se.Message;
return;
}
catch (Exception e)
{
lbReception.Text = "异常:" + e.Message;
return;
}
if (arrMsgRec[] == ) // 表示接收到的是消息数据;
{
string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec, , length - );// 将接受到的字节数据转化成字符串;
lbReception.Text = strMsg;
}
}
}
#endregion
#endregion #region 发送数据
/// <summary>
/// 发送数据
/// </summary>
/// <param name="s"></param>
public void send(string s)
{
try
{
byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(s);
byte[] arrSendMsg = new byte[arrMsg.Length + ];
arrSendMsg[] = ; // 用来表示发送的是消息数据
Buffer.BlockCopy(arrMsg, , arrSendMsg, , arrMsg.Length);
sockClient.Send(arrSendMsg); // 发送消息;
}
catch (Exception)
{ throw;
} }
#endregion