Created
June 30, 2016 18:50
-
-
Save sichbo/77615b5c0a6ef7f0fab367862bffb1bd to your computer and use it in GitHub Desktop.
Unix TcpListener bug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Threading.Tasks; | |
using System.Threading; | |
namespace TcpListenerTest | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var sync = new AutoResetEvent(false); | |
RunServer(sync); | |
sync.WaitOne(); | |
HitServer(sync); | |
sync.WaitOne(); | |
Console.WriteLine("Hit a key to close and reopen..."); | |
Console.ReadLine(); | |
// On second run (Unix only) TcpListener.Start throws: | |
// Unhandled Exception: System.Net.Sockets.SocketException: Address already in use | |
// at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) | |
// at System.Net.Sockets.Socket.Bind(EndPoint localEP) | |
// at System.Net.Sockets.TcpListener.Start(Int32 backlog) | |
// at System.Net.Sockets.TcpListener.Start() | |
// at TcpListenerTest.Program.<RunServer> d__1.MoveNext() | |
RunServer(sync); | |
sync.WaitOne(); | |
HitServer(sync); | |
sync.WaitOne(); | |
// We get here under Windows just fine | |
Console.WriteLine("OK, that worked fine."); | |
Console.ReadLine(); | |
} | |
async static void RunServer(AutoResetEvent sync) { | |
var listener1 = new TcpListener(IPAddress.Any, 7000); | |
Console.WriteLine("Server starting"); | |
listener1.Start(); | |
sync.Set(); | |
var client = await listener1.AcceptTcpClientAsync(); | |
Console.WriteLine("Server got connection"); | |
client.Dispose(); | |
listener1.Stop(); | |
Console.WriteLine("Server stopped"); | |
} | |
async static void HitServer(AutoResetEvent sync) { | |
using (var client = new TcpClient()) { | |
Console.WriteLine("Client connecting"); | |
await client.ConnectAsync(IPAddress.Parse("127.0.0.1"), 7000); | |
} | |
Console.WriteLine("Client disconnected"); | |
sync.Set(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment