【发布时间】:2013-11-30 17:04:10
【问题描述】:
这是我第一次使用 Windows Form 应用程序做套接字服务器/客户端。
我在public void Listen() 下的Socket.bind(IPEndpoint) 遇到了问题。我得到了错误
每个套接字地址(协议/网络地址/端口)通常只允许使用一次
有什么想法可以解决这个问题吗?
public Form1()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
Socket sck;
Socket acc;
IPEndPoint ipe;
List<Socket> lstClient = new List<Socket>();
Thread handleClient;
string myIP = "";
public void IP()
{
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress address in host.AddressList)
{
if (address.AddressFamily.ToString() == "InterNetwork")
{
myIP = address.ToString();
}
}
ipe = new IPEndPoint(IPAddress.Parse(myIP), 2001);
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);
}
private void btnListen_Click(object sender, EventArgs e)
{
this.Form1_Load(sender, e);
}
private void rtbMain_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
IP();
handleClient = new Thread(new ThreadStart(Listen));
handleClient.IsBackground = true;
handleClient.Start();
}
public void Listen()
{
sck.Bind(ipe);
sck.Listen(3);
while(true)
{
Socket acc=sck.Accept();
lstClient.Add(acc);
Thread clientProcess = new Thread(myThreadClient);
clientProcess.IsBackground = true;
clientProcess.Start(acc);
rtbMain.SelectionFont = new Font("Arial", 18, FontStyle.Bold);
rtbMain.SelectionColor = Color.Green;
rtbMain.AppendText("accept connections from" +
acc.RemoteEndPoint.ToString());
rtbMain.ScrollToCaret();
}
}
private void myThreadClient(object obj)
{
Socket clientACC = (Socket)obj;
while(true)
{
byte[] sizeBuf = new byte[1024];
int rec = clientACC.Receive(sizeBuf);
foreach (Socket acc in lstClient)
{
acc.Send(sizeBuf,sizeBuf.Length,SocketFlags.None);
}
}
}
【问题讨论】:
-
那么您是否尝试将多个套接字绑定到同一个协议/地址/端口?
-
基本上我希望我的服务器在客户端/多个客户端连接到它时进行监听,如果有意义的话,基本上是通过 IP 地址设置的聊天服务器/客户端?
标签: c# multithreading winforms sockets binding