Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0 udp Sockets
Hi,
I've written a basic UDP client/server app. The client works fine as does the server but as soon as I shut the server down and start it up again, it freezes. C~ gives me the following error message:
 
"An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
 
Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted"
 
The line of code it refers to is
 UdpClient udpClient = new UdpClient(8080);
 
If I reboot my PC it will re-compile and work.
 
The code is below - I assume as there is no formal shut down for the server, the port is still reserved somehow.
 
The code for the server is below. Thanks.
 

 
public void serverThread()
{
    UdpClient udpClient = new UdpClient(8080);
    while (true)
    {
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
        string returnData = Encoding.ASCII.GetString(receiveBytes);
        lbConnections.Items.Add(RemoteIpEndPoint.Address.ToString() + ":" + returnData.ToString());
    }
}
public Form1()
{
    InitializeComponent();
}
 
private void Form1_Load(object sender, EventArgs e)
{
    Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
    thdUDPServer.Start();
}
Posted 31-Oct-12 11:13am
Comments
Mathlab at 31-Oct-12 17:07pm
   
Is the error happening when you call thdUDPServer.Start() or when you initialize the thread?
Ed Nutting at 31-Oct-12 18:37pm
   
There are so many things wrong with the code here that he will continue to receive errors for a while to come... See my Solution which points out just a few of the most obvious flaws. The implementation above is best described as "incomplete". A good start though so good luck to the OP!
 
Ed
Mathlab at 1-Nov-12 10:15am
   
I think your solution has some merrit but his code is incomplete I dont see where he set up a listener on one end and a sender on other. I dont see his .Connect statement and the client code is incomplete.
Ed Nutting at 1-Nov-12 10:31am
   
UDP doesn't necessarily require a connection if the OP is only interested in broadcast packets so .Connect() may not be required. Since this is only the server, .Connect() is certainly not required but I'll agree he perhaps ought to listen for connections (again depends on what OP is trying to do). He has only presented the server end so we cannot really know what he is trying to achieve/receive. I will agree at the moment this code is horribly incomplete and I did only provide details of a few of the basic flaws in it. I would advise the OP to try TCP first then do UDP, since TCP is significantly simpler to get right and there is only really one version of it, unlike UDP where there are two (i.e. connected and connectionless).
 
I would not expect the OP to have posted any client code (which he hasn't - only server code). Worth noting that you can use a UDPClient to run a server which often causes immense confusion. Anyway, I would not expect any code for sending data either, since none of that is required to write/run a UDP server (though using it for testing is very helpful).
 
Thank you for your comment, I do agree the OP has a long way to go, but the question itself was not so bad - at least it had an error, unlike so many of the questions we see on CP!
Ed :)
Sergey Alexandrovich Kryukov at 31-Oct-12 20:15pm
   
What do you mean "re-compile"? How recompilation is related to repeated run? You could simply copy executable modules and see if one changed (which is very unlikely, or would mean virus). I simply don't think your observations are accurate, and/or you don't understand the life cycle: what compilation, JIT and loading do...
--SA
Sergey Alexandrovich Kryukov at 16-Feb-13 19:50pm
   
Please stop posting your comments as "solution". You can add comment to any post, reply to existing comments, use "Improve question".
—SA

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi there,
 
Are you disconnecting/stopping listening from the port properly? It doesn't look like you are. If you aren't, the port will look like it is already being listened after you close your program and thus when you try to run your program a second time. Since two things can't listen on the same port at once, you get an error. You then need to restart your computer to fix the issue (which matches the behaviour you are experiencing). You need to call Close() on the port to end your "Receive" properly.
 
Also, check that all your threads end properly. Often the UI thread ends but your program hasn't actually ended as background threads may still be running. At the moment your background listening thread has while(true) - so it will never end as you have no break or return statements! You should have a global boolean called "ShouldTerminate". Then handle the Form's "Closing" event and set ShouldTerminate to true. Finally, change your 'while' loop to "while(!ShouldTerminate)".
 
You will also need to find a way of cancelling the "Receive" call reliably. I think Close does this but that results in you receiving 0 bytes of data which you then need to check for. If you don't find a way of cancelling the Receive, your thread will pause indefinitely until it receives data, even after the rest of the program ends, which would then keep your thread alive and thus your program running.
 
In my experience it is far better is to use the ReceiveAsync method (or similar name - not 100% sure - been 12 months since I used this sort of code) and build your program round that system of message handling (i.e. Asynchronous messages/events) - that way you can cancel receive calls etc. easily and thus close your program cleanly. You also avoid hanging threads.
 
Hope this helps,
Ed
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 480
1 Maciej Los 290
2 Richard MacCutchan 225
3 BillWoodruff 185
4 Suraj Sahoo | Coding Passion 155
0 OriginalGriff 8,764
1 Sergey Alexandrovich Kryukov 7,437
2 DamithSL 5,639
3 Maciej Los 5,279
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web03 | 2.8.1411028.1 | Last Updated 1 Nov 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100