Trying to start a listener socket - c#

I have tried to follow the exmaple on the MSDN to create an async server. But nothing seems to be able to connect to it.
http://msdn.microsoft.com/en-us/library/5w7b7x5f.aspx
Here's what I have...
Also notice the AddressList[2], this is not a mistake ;)
private static Socket mListenerSocket;
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList[2], port);
// This line outputs 192.168.0.6:6809 (which is correct)
Console.WriteLine("{0}", localEP.ToString());
mListenerSocket = new Socket(
ipHostInfo.AddressList[2].AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
mListenerSocket.Bind(localEP);
mListenerSocket.Listen(10);
mListenerSocket.BeginAccept(new AsyncCallback(AcceptCallback), mListenerSocket);
My callback mathod is defined as:
private static void AcceptCallback(IAsyncResult ar)
{
// It does not even get here
mListenerSocket.EndAccept(ar);
}
I would expect when I telnet using 'telnet 192.168.0.6 6809' it should jump to the AcceptCallback method, but it doesn't, so a connection isnt established.
So any ideas why it doesnt work? The are no errors to help me :(
I have tried using a TcpListener instead, but again to still no avail :(
mListenerSocket = new TcpListener(IPAddress.Any, port);
mListenerSocket.Start();
mListenerSocket.BeginAcceptSocket(new AsyncCallback(AcceptCallback), mListenerSocket);

My firewall was preventing connections to the client. Even though I disabled it, I had to restart Visual Studio to capture it.

Related

How to disconnect from one end point and then connect to another? - C#

I have two servers and a client. One server is on the same computer where the client is. I need to disconnect from the local server and connect to the remote one.
AutoResetEvent disconnectDone = new AutoResetEvent(false);
IPEndPoint localEndPoint = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], PORT);
Socket socket;
// somewhere I initialize the socket and connect to the local end point
public void someButton_Click(object sender, EventArgs e)
{
string IP = someTextBox.Text;
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
socket.BeginDisconnect(true, DisconnectCallback, socket);
disconnectDone.WaitOne();
}
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), PORT);
socket.BeginConnect(remoteEndPoint, ConnectCallback, socket);
}
private void DisconnectCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndDisconnect(AR);
disconnectDone.Set();
}
It freezes at the line with the WaitOne method because DisconnectCallback doesn't answer.
If in the BeginDisconnect method I change true to false then it "works". But further BeginConnect gives me an exception that the socket is still connected.
I really do not understand how all these disconnect things work. Or maybe I'm wrong with those thread methods (WaitOne and Set). Please help!

Suddenly server cannot connect due to SocketException

I am using this server example from MSND: http://msdn.microsoft.com/en-us/library/fx6588te.aspx
and from some reason my server refuse to connect at this function at _listener.Bind(localEndPoint); with error Only one usage of each socket address (protocol/network address/port) is normally permitted
Until a few minutes ago I had no problems Sarver connect without problems and suddenly it happens
public static void StartListening(IPAddress ipAddress, int port)
{
_isServerRunning = true;
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
//IPAddress ipAddress = IPAddress.Parse("192.168.0.100"); //ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
_listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
_listener.Bind(localEndPoint);
_listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
_listener.BeginAccept(
new AsyncCallback(AcceptCallback),
_listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
What does this error means ?
It most likely means that the local port is still reserved. This can be idther because another process is still runnoing and holding the sockewt open, or because the timeout period defined by th dSO_LINGER socket option is not timed out. I'm not familiar with c# but there should be a way to set th elinger timeout.
You can tell the current status of the socket by using the netstat command.
I think you can find some solutions here http://blogs.msdn.com/b/dgorti/archive/2005/09/18/470766.aspx

beginAccept() asynchronous server issue in C#

I'm struggling with some piece of simple code. However, I can't get it done. I have this server, which must accept connections from multiple clients (asynchronously, obviously). So, I have:
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 8082);
TcpListener tcpListener = new TcpListener(IPAddress.Any, 8082);
server = tcpListener.Server;
server.Bind(ipEndPoint);
server.Listen(4);
server.BeginAccept(new AsyncCallback(beginConnection), server);
And,
static void beginConnection(IAsyncResult iar)
{
Console.WriteLine("Client connected");
Socket s = (Socket)iar.AsyncState;
server = s.EndAccept(iar);
server.Listen(4);
server.BeginAccept(beginConnection, s);
}
Then, when I try to connect myself, the first client works OK. It just sends a message to this server, and the server sends it back to the client. The server functions as an echo. But when I try to connect another clients it doesn't work. I have also put the Console.WriteLine("Client connected"), but the server doesn't write anything.
How can I fix this problem?
I think I'm not passing the right parameter to the first BeginAccept method. Instead of server socket, I should be passing the tcpListener.
Then I would have:
static void beginConnection(IAsyncResult iar)
{
Console.WriteLine("Client connected");
TcpListener tcpListener = (TcpListener)iar.AsyncState;
Socket s = tcpListener.Server.EndAccept(iar);
tcpListener.Server = s; // But I would have this error
server.Listen(2);
server.BeginAccept(beginConnection, s);
}
But I would have the error that I marked it up. In the first version nothing is modified, so I think this it's the issue in the first version of the code.
First, you do not need the Server property of the TcpListener. You should simply call Start(), even without Bind.
Second, EndAccept() is also should be called at TcpListener and return a TcpClient instance which you must use for sending and receiving data.
A simple example of what I just said might be presented as:
{
TcpListener listener = new TcpListener(IPAddress.Any, 8082);
listener.Start();
AcceptClient();
}
void AcceptClient()
{
listener.BeginAccept(ClientConnected, null);
}
void ClientConnected(IAsyncResult ar)
{
TcpClient client = listener.EndAccept();
AcceptClient();
// Now you can send or receive data using the client variable.
}

How to make more than 1 socket to the same host and port?

I am trying to forward multiple sockets communication to a target socket. So I need to make multiple connection to that target socket, but when I try to connect to it for the second time, I get this:
SocketException: No connection could be made because the target machine actively refused it
I think the problem is with the other end of the socket, i.e port and host and because there is already a connection between port related to my program and target port, to have a second connection I need a second port for my program.
I hope my problem be clear for you guys.
Any Idea how to do it?
This is a test program just to show the problem.
using System;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Text;
class Sample
{
private static ManualResetEvent connectDone = new ManualResetEvent(false);
public static void Main()
{
Socket[] s = new Socket[10];
for (int i = 0; i < s.Length; i++)
{
IPAddress ipAddress;
ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndp = new IPEndPoint(ipAddress, 1100);
// Create a TCP/IP socket.
s[i] = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
connectDone.Reset();
s[i].BeginConnect(localEndp,
new AsyncCallback(ConnectCallback), s[i]);
connectDone.WaitOne();
s[i].Send(Encoding.ASCII.GetBytes(i.ToString() + ": hi.\r\n"));
}
}
private static void ConnectCallback(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
// Signal that the connection has been made.
connectDone.Set();
}
}
I even tried to bind my sockets to different ports, but still second socket gets that exception.
This error message means that there is no open port on that IP. The IP is valid but the remote host replied that it will not accept a connection on this port.
You should be getting this error even for the very first connection.
Find out why the port is not open.
Btw, you use of async connect is counter-productive. You have non of the async benefits and all of the disadvantages. But this is not the point of this question.

Trouble getting sockets to connect in windows7 64bit

Hey. I've been searching around for a solution to this problem with no luck. I was wondering if this is a known issue when switching socket code from WinXP 32 bit to Win7 64 bit. I have a fairly simple socket routine which works fine in WinXP 32bit, but the socket.connect call is throwing the exception "No connection could be made because the target machine actively refused it 127.0.0.1:48000"
I've added an exception to the win7 firewall for the program, and doubled checked to make sure the rule it added was allowing all ports.
The code I use to setup these simple sockets is as follows:
Listening Socket:
byte[] bytes = new Byte[8192];
IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 48000);
_ListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
_ListenerSocket.Bind(localEndPoint);
_ListenerSocket.Listen(1000);
while (_Running)
{
_ListenerSync.Reset();
_ListenerSocket.BeginAccept(new AsyncCallback(AcceptCallback), _ListenerSocket);
_ListenerSync.WaitOne();
}
_ListenerSocket.Shutdown(SocketShutdown.Both);
_ListenerSocket.Close();
}
Connecting Socket:
IPAddress _IP;
IPAddress.TryParse("127.0.0.1", out _IP)
Socket tTarget = null;
if (tTarget == null)
{
tTarget = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
tTarget.Connect(_IP, 48000);
_Connected = true;
byte[] tBuffer = new byte[8192];
string tRecvBuff = "";
while (_Connected)
{
int tRecv = tTarget.Receive(tBuffer);
//{ does stuff here }
}
Seems like everything works until tTarget.Connect(), where it pauses for a second and then throws the exception listed above. AcceptCallback is never called.
Thanks.
Based on your comment your listening on IPV6. Instead of
ipHostInfo.AddressList[0]
try
ipHostInfo.AddressList.ToList().Find(p=>p.AddressFamily==AddressFamily.InterNetw‌​ork);

Categories