Reputation: 87
This is the first time I have used Windows Form application to do a socket server / client.
I have ran into a problem with my Socket.bind(IPEndpoint)
under my public void Listen()
. I get the error
Only one usage of each socket address (protocol/network address/port) is normally permitted
Any ideas how I could go about fixing this?
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);
}
}
}
Upvotes: 1
Views: 1797
Reputation: 73442
This could happen if a socket is already listening in same port in your application any other process.
Just make sure no apps us it, and make sure you don't run multiple instances of your same application(verify it with taskmanager).
CheckForIllegalCrossThreadCalls = false
Your IP
method doesn't makes sense to name it as IP
. I'd rather name it as GetIPAndCreateSocket
or something like that.
Method name should tell us what that method is going to do.
Upvotes: 1