[英]Display Multiple clients Name at Server side using Socket Connection in WinForms C#
In Windows-Form Application C# , I have done multiple client connection to a single server using socket connection and I can send numbers from multiple clients to single server. 在Windows-Form Application C#中 ,我已经使用套接字连接完成了到单个服务器的多个客户端连接,并且可以将多个客户端的编号发送到单个服务器。 But the problem is that, at the server I am not able to differentiate which client is sending which number, so I need to display
Client_1
, Client_2
, Client_3
and so on differently at the server side application. 但是问题在于,在服务器上,我无法区分哪个客户
Client_3
在发送哪个号码,因此我需要在服务器端应用程序中以不同的方式显示Client_1
, Client_2
, Client_3
等。 Please let me know how it would be better? 请让我知道会更好吗?
SERVER( at the OnDataReceived() Method how it can be changed?) SERVER(如何更改OnDataReceived()方法?)
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 Socket_Server
{
public partial class Form1 : Form
{
const int MAX_CLIENTS = 30;
public AsyncCallback pfnWorkerCallBack;
private Socket m_mainSocket;
private Socket[] m_workerSocket = new Socket[30];
private int m_clientCount = 0;
public StreamWriter STW;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string PortNumber = "1755";
try
{
string portStr = PortNumber;
int port = System.Convert.ToInt32(portStr);
m_mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
m_mainSocket.Bind(ipLocal);
m_mainSocket.Listen(4);
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
this.BackgroundWorker = new Thread(new ThreadStart(Startinfiniteloop));
this.BackgroundWorker.Start();
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void Startinfiniteloop()
{
for (int initial_value = 0; ; initial_value++)
{
try
{
Dictionary<string, int> d2 = new Dictionary<string, int>();
d2["c2"] = initial_value;
this.BeginInvoke((MethodInvoker)(() => Storing_Number.Items.Clear()));
this.BeginInvoke((MethodInvoker)(() => Storing_Number.Items.Add(d2["c2"])));
//Delay Thread
Thread.Sleep(1000);
NumberSend( d2["c2"] + "\n");
this.BeginInvoke((MethodInvoker)(() => Sending_Box.Items.Add("Sending_To_CLIENT: " + d2["c2"] + "\n")));
this.BeginInvoke((MethodInvoker)(() => Sending_Box.TopIndex = Sending_Box.Items.Count - 1));
// this.BackgroundWorker = new Thread(new ThreadStart(NumberSend));
// this.BackgroundWorker.Start();
// STW = new StreamWriter(Sending_Box.Items[initial_value].ToString());
// STW.WriteLine(Sending_Box.Items[initial_value]);
// STW.AutoFlush = true;
}
catch (Exception x)
{
}
}
}
public void NumberSend(string mesg)
{
try
{
Object objData = mesg;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
for (int i = 0; i < m_clientCount; i++)
{
if (m_workerSocket[i] != null)
{
if (m_workerSocket[i].Connected)
{
m_workerSocket[i].Send(byData);
}
}
}
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
WaitForData(m_workerSocket[m_clientCount]);
++m_clientCount;
String str = String.Format("Client # {0} connected", m_clientCount);
Invoke(new Action(() => textBoxMsg.Clear()));
Invoke(new Action(() => textBoxMsg.AppendText(str)));
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public class SocketPacket
{
public System.Net.Sockets.Socket m_currentSocket;
public byte[] dataBuffer = new byte[1024];
}
public void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket();
theSocPkt.m_currentSocket = soc;// could be this one!!!
soc.BeginReceive(theSocPkt.dataBuffer, 0,
theSocPkt.dataBuffer.Length,
SocketFlags.None,
pfnWorkerCallBack,
theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;
iRx = socketData.m_currentSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(socketData.dataBuffer,
0, iRx, chars, 0);
System.String szData = new System.String(chars);
Invoke(new Action(() => richTextBoxSendMsg.AppendText(szData)));
Invoke(new Action(() => richTextBoxSendMsg.AppendText(Environment.NewLine)));
WaitForData(socketData.m_currentSocket);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
CloseSockets();
Close();
}
String GetIP()
{
String strHostName = Dns.GetHostName();
IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
String IPStr = "";
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
if (ipaddress.IsIPv6LinkLocal == false)
{
IPStr = IPStr + ipaddress.ToString();
return IPStr;
}
}
return IPStr;
}
void CloseSockets()
{
if (m_mainSocket != null)
{
m_mainSocket.Close();
}
for (int i = 0; i < m_clientCount; i++)
{
if (m_workerSocket[i] != null)
{
m_workerSocket[i].Close();
m_workerSocket[i] = null;
}
}
}
public Thread BackgroundWorker { get; set; }
}
}
In OnClientConnect()
, the IAsyncResult object should have information on the client. 在
OnClientConnect()
,IAsyncResult对象应具有有关客户端的信息。 Where you do ++m_clientCount;
您在哪里
++m_clientCount;
you could setup a dictionary with the unique info from each client and their ID (IP, port). 您可以使用每个客户端的唯一信息及其ID(IP,端口)来设置字典。 Then in
OnDataReceived()
you could just GetClientID(Socket client)
. 然后在
OnDataReceived()
您可以只是GetClientID(Socket client)
。
More info can be found on: https://msdn.microsoft.com/en-us/library/bbx2eya8(v=vs.110).aspx 可以在以下网址找到更多信息: https : //msdn.microsoft.com/en-us/library/bbx2eya8(v=vs.110).aspx
Note that in the future, please post a simplest version of your issue, so that others don't have to go through the entire code. 请注意,将来,请发布问题的最简单版本 ,这样其他人就不必遍历整个代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.