Tcp Server Only Allowing 1 Client - c#

Server.cs - https://hastebin.com/enajinewij.cs
Client.cs - https://hastebin.com/iriperubur.cs
I have tried both running the Client on another PC and running it on one PC, but both result in the Client not being able to receive or send any messages.
I CANT portforward. I am using Hamachi for the IP Address. Both client and server are connected to my Network and are using the Hamachi IP Address. I am using PDA Net to connect to the internet from my PC.
The Server does not see them connect at all. Nor does the Server get any messages from them. Currently only the Server can send messages, and only it can get them.
I am not getting ANY errors at all, so I am not sure how I should handle solving this issue as it's my first time working with networking.

At first you create a TcpListener and you call StartLis() that does BeginAcceptTcpClient. However in AcceptTCPClient you create a new TcpListener and BeginAcceptTcpClient is not called.
You don't have to create a new listener for each connection, but you do have to call BeginAcceptTcpclient again:
private void AcceptTCPClient(IAsyncResult ar)
{
TcpListener Lis = (TcpListener)ar.AsyncState;
Clients.Add(new ServerClient(Lis.EndAcceptTcpClient(ar)));
StartLis(); // this will call BeginAcceptTcpClient again
}

Related

UDP UWP server + Mono2x client

I have a really weird issue with communication between server and client using UDP protocol. Client is written in Mono2x (I use Unity 3D as my client) and creates UdpClient class instance:
_udpClient = new UdpClient(9050);
_serverEP = new IPEndPoint(IPAddress.Parse(_serverIp), _serverPort);
My server is UWP application I want to run on Raspberry Pi that is using DatagramSocket:
_udpServer = new DatagramSocket();
_udpServer.MessageReceived += ClientCheck;
await _udpServer.BindServiceNameAsync(port.ToString());
I send data from client to server but with no luck. I checked with TCPView that data is send from my client application but never reaches the server. And now is the weird part. When I receive message from server first (I hardcode port to client), my client is able to send data with a success.
I am using same IPEndPoint to send data from client without any changes after receiving packet from server, it just starts working. Honestly, I have no idea what I could do wrong, so I will be thankful for any advice.
And now is the weird part. When I receive message from server first (I hardcode port to client), my client is able to send data with a success
This is a known issue which is filed based on this related question: https://stackoverflow.com/a/39767527/5254458
It includes the issue's description and temporary workaround.
The corresponding is team is investigating it and I can not guarantee that when the fix will be delivered.

Connection specific AppendShutdownHandler

I'm using NetworkComms.Net and I'm currently trying to create a sort of forwarder which listens on a port (calling it GATEWAY), which receive a certain packet (from CLIENT) which will tell him where to redirect next pacekts coming from the same client.
Example:
CLIENT tell GATEWAY that he needs to get to SERVER:serverport
GATEWAY creates a connection to SERVER:serverport
CLIENT sends packets to GATEWAY which sends them to SERVER
SERVER sends back a response, which goes through the GATEWAY to the CLIENT.
I had it working with Net.Sockets and I’m now changing to NetworkComms.
The problem I’m facing is that when a connection from Gateway (client) to Server (listening server) is closed, the Gateway trigger the global callbacks for connection/disconnection:
NetworkComms.AppendGlobalConnectionCloseHandler(ClientDisconnected);
NetworkComms.AppendGlobalConnectionEstablishHandler(ClientConnected);
Those callbacks are supposed to be only called when a client connect or disconnect on the Gateway
This is the code i’m currently using to start the listener.
NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions<ProtobufSerializer, , LZMACompressor>();
NetworkComms.DefaultSendReceiveOptions.IncludePacketConstructionTime = NetworkComms.DefaultSendReceiveOptions.ReceiveHandlePriority = QueueItemPriority.AboveNormal;
NetworkComms.AppendGlobalConnectionCloseHandler(SessionClosed);
NetworkComms.AppendGlobalConnectionEstablishHandler(NewSessionConnected);
NetworkComms.AppendGlobalIncomingPacketHandler<string>("ECHO", SocketCommands.HandleIncomingECHOPacket);
Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 10000));
I suppose this is like a “global” way of starting It?
How do I start one then add those Connected/Disconnected handlers to just the listener?
Thanks

No connection could be made because the target machine actively refused it [not similar to others]

I'm trying to learn Socket Programming, and I encountered this error while connecting to my server application.
Here's my declaration of the TcpListener in the server application:
TcpListener listener = new TcpListener(IPAddress.Loopback, 5152);
and here's my declaration of the TcpClient in my client application:
TcpClient client = new TcpClient(Dns.GetHostEntry(IPAddress.Loopback).HostName, 5152);
I have read several questions like this, and I always get the same answer: Either the server application isn't listening to the port or not running at all. But I've double-checked the Resource Monitor and cmd using netstat to see if the service is listening to the port, and it is. I've also included the service in the Firewall exceptions, so I'm not sure why I keep getting this error while trying to connect to the server app.
Any ideas?
Dns.GetHostEntry(IPAddress.Loopback).HostName returns the host name of your machine. When you pass a host name to TcpClient, it will resolve it to one or more IP addresses using Dns.GetHostAddresses(hostName). This includes the public and link-local IP addresses of your machine (e.g., 192.168.15.4), but not the loopback address (127.0.0.1).
So your client is trying to connect to any of the non-loopback addresses of your machine, while your server is listening only on the loopback address. Thus, no connection can be established.
Solution: Connect to the same end point your server is listening on.
IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 5152);
TcpListener listener = new TcpListener(endPoint);
TcpClient client = new TcpClient();
client.Connect(endPoint);

TCP Connect to Azure Fails

I recently deployed an Azure app to the staging environment which is supposed to accept TCP packets in port 2993. When run in the Azure emulator, it does this very well, and performs exactly as it should.
However, now that it is on Azure's staging servers, whenever I try to connect to the TCP port, i get the following SocketException:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
My web app has two instances, one is a worker role (it has 2993 configured in its endpoints) and a web role (only for port 80). Port 80, by the way, functions perfectly. The web app was created with Visual Studio in C#. Why is this happening and how can I fix it?
All help is greatly appreciated.
I would like to explain what was the issue and why adding above code solve this problem for others benefit.
In your worker role, you configure any TCP endpoint along with any port number. When this VM starts the VM is provisioned to use this port and firewall is included an exception to provide access to this port. By the time your is ready to start your Azure VM already have TCP/IP address and configured port is enabled.
Now when your role starts and if you have any service or application required access this port you really need to l
For example If I have Tomcat/Java configured in my worker role, I must have to create a TCP listener on my configured port. This can be done when my worker role starts as below:
Get the IP address and Port number of the current role instance
Create a TCP Listener and start on this IP address and Port
Add the code to perform step 1) and 2) in my worker role OnStart() function.
The code will look like as below:
TcpListener TomcatPortListener = new TcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["TomcatWeb80"].IPEndpoint);
TomcatPortListener.Start();
In your case you you did exactly the same you got the IP address and Port number from and then created an endpoint from a socket address using IP/Port:
RoleInstanceEndpoint externalEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["TCPin"];
IPEndPoint localEndPoint = new IPEndPoint(externalEndPoint.IPEndpoint.Address, externalEndPoint.IPEndpoint.Port);
localEndPoint.Create();
It is a must setting for any web or worker role which create TCP endpoint.
It seems the problem had something to do with the program's detection of the server's IP address. By using the following server code instead, I managed to fix the problem:
RoleInstanceEndpoint externalEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["TCPin"];
IPEndPoint localEndPoint = new IPEndPoint(externalEndPoint.IPEndpoint.Address, externalEndPoint.IPEndpoint.Port);
The IPEndpoint can then be used with the tcpListener socket.

Server/client sockets

Ok so I am new to socket programing and I'm making a game that is going to run from a server. I am going to try to be able to get a hundred clients to run off my server. Should I make one listener instance or one for every client? Also I've tried to make a hundred listeners all at 100 different ports but when I run my server I get an error while trying to start my listeners. The game is going to be a 3D RPG/MMORPG. Most of the game logic is in the clients though. What do you think that I should do?
If you are going to use TCP sockets, then you should create one listener socket (i.e. create a socket, bind it to a specific port and call Listen() on it). Then, when you Accept a connection and get another socket, which you use for receiving/sending data from/to client:
Socket socketListener;
// create listening socket
socketListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 30120); // use port 30120
//bind to local IP Address.
socketListener.Bind(ipLocal);
//start listening
socketListener.Listen(4);
while (true) // loop that accepts client connections
{
Socket socketWorker = socketListener.Accept();
HandleClientConnection(socketWorker); // your routine where you communicate with a client
}
Also, consider using sockets in asynchronous mode, that will be more efficient in terms of performance.
You only ever have one listener per server endpoint. The listener will then create a connection for the client that uses a different port. It is this connection you actually use for communication.

Categories