Tcp connection fails on LAN - c#

I am trying to send a message from my laptop to my desktop over the LAN.
I have written a Tcp server that listens for a connection on a port, and a client that tries to connect to it and send a simple string as a message.
Server:
void Listen()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
while (true)
{
Debug.Log($"listening to {listener.LocalEndpoint}...");
var socket = listener.AcceptSocket();
Debug.Log("connected!");
var bytes = new byte[100];
int k = socket.Receive(bytes);
var data = Encoding.ASCII.GetString(bytes, 0, k);
Debug.Log(data);
socket.Send(new byte[] {1});
Debug.Log("responded");
socket.Close();
Debug.Log("closed connection");
}
}
Client:
public void Send()
{
client = new TcpClient();
Debug.Log("connecting...");
client.Connect("192.168.0.12", port);
Debug.Log("connected!");
var data = Encoding.ASCII.GetBytes("Hello!");
var stream = client.GetStream();
Debug.Log("sending data");
stream.Write(data, 0, data.Length);
Debug.Log("data sent! waiting for response...");
var reply = new byte[100];
stream.Read(reply,0,100);
Debug.Log("received response");
client.Close();
}
They communicate correctly when they are both on the same machine, but the client never connects to the server when I am running it on a different machine.
I have a rule in my firewall that allows an incoming connection through the port I have specified.
I have tried it with both computer's firewalls off and the connection still doesn't go through.
Any help would be greatly appreciated.

Related

Connection Refused with TCP socket Error # 10061

I'm creating a small chat (1-1) application to learn network programming and when creating the socket using TCP protocol, the Socket.Connect() always return error 10061.
However, if I make the socket UDP, I don't see the issue.
Here is my code:
myEndPoint = new IPEndPoint(IPAddress.Parse(_txtMyIPAdress.Text), int.Parse(_txtMyPort.Text));
TargetSideEndPoint = new IPEndPoint(IPAddress.Parse(_txtTargetIPAddress.Text), int.Parse(_txtTargetPort.Text));
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
mySocket.Bind(myEndPoint);
mySocket.Connect(TargetSideEndPoint);
byte[] receivedBuffer = new byte[MAX_BUFFER_SIZE = 1024];
ReceivePackets(mySocket, receivedBuffer);//My function
Can any one help me?
Update:
I'm not using Listen() the issue is when I call Connect()
I already tried multiple ports with the same issue and I'm currently testing on 1 PC by opening 2 instances from my application and using 2 different ports while firewall is off.
Thanks,
For TCP, which is a connection oriented protocol, you would need a server and a client.
The server must listen for incoming connections and the client should initiate the connection. Then, the client will be able to communicate with the server and exchange data.
Here is a simple working example:
void Main()
{
Console.WriteLine("Starting listener thread");
Thread serverThread = new Thread(ListenerThreadProc);
serverThread.Start();
Console.WriteLine("Waiting 500 milliseconds to allow listener to start");
Thread.Sleep(500);
Console.WriteLine("Client: Connecting to server");
TcpClient client = new TcpClient();
client.Connect(IPAddress.Loopback, 12345);
Console.WriteLine("Client: Connected to server");
byte[] buffer = new byte[5];
Console.WriteLine("Client: Receiving data");
using (NetworkStream clientStream = client.GetStream())
clientStream.Read(buffer, 0, buffer.Length);
Console.WriteLine("Client: Received data: " + buffer.Aggregate("", (s, b) => s += " " + b.ToString()));
}
void ListenerThreadProc()
{
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
Console.WriteLine("Server: Listener started");
Console.WriteLine("Server: Waiting for client to connect");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Server: Client connected");
listener.Stop();
Console.WriteLine("Server: Listener stopped");
Console.WriteLine("Server: Sending data");
byte[] buffer = new byte[] { 1, 2, 3, 4, 5 };
using (NetworkStream clientStream = client.GetStream())
clientStream.Write(buffer, 0, buffer.Length);
Console.WriteLine("Server: Sent data");
}
In this example, made as simple as it gets, you have a server accepting a single client to which it sends some data. The client connects, reads the data and then displays it.
A real-life server would spin new threads (or tasks, for async model) to serve the client's request as soon as the client would connect and carry on listening for new connections.

c# client-server using UDP Connection

I am trying to make client Server appilcation in c#. On the Client side i write hello message to Server and Server receives the message.
once the Server receive the message, it should send back client a messsage indicating that message has been received. Basically an acknowledment.
My Problem is that Client doesn´t receive the message form Server.
On down is my code for both Client and Server.
Client part:
string x = "192.168.1.4";
IPAddress add = IPAddress.Parse(x);
IPEndPoint point = new IPEndPoint(add, 2789);
using (UdpClient client = new UdpClient())
{
byte[] data = Encoding.UTF8.GetBytes("Hello from client");
client.Send(data, data.Length, point);
string serverResponse = Encoding.UTF8.GetString(client.Receive(ref point));
Console.WriteLine("Messahe received from server:"+ serverResponse);
}
Server part:
try
{
while (true)
{
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 2789);
Console.WriteLine("Client address is:" + groupEP.Address.ToString());
Console.WriteLine("Client port is:" + groupEP.Port.ToString());
byte[]data = new byte[1024];
UdpClient listener = new UdpClient(2789);
Console.WriteLine("Waiting for client");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine("Received Data:"+ Encoding.ASCII.GetString(bytes, 0, bytes.Length));
//sending acknoledgment
string welcome = "Hello how are you from server?";
byte[]d1 = Encoding.ASCII.GetBytes(welcome);
listener.Send(d1, d1.Length, groupEP);
Console.WriteLine("Message sent to client back as acknowledgment");
}
}
I compiled your code and it work so your issue is an "outside" problem such as :
A firewall is blocking something (either the connection or the server binding).
Because the ip in your sample is a lan ip it is probably the built-in firewall from Windows (or a third-party firewall).
Try to disable your firewall, here is how to disable the built-in firewall of Windows.
You test the client on a different computer than the server and use the wrong ip.
If you do test on the same machine you may use the special ip 127.0.0.1 (aka the DNS localhost). 127.0.0.1 always refer to the computer that is running the code. Using this special ip may avoid you trouble in future if your local ip does changes.
And by the way, in your server code you should reuse the "listener" field for each interation of while() such as in
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 2789);
Console.WriteLine("Client address is:" + groupEP.Address.ToString());
Console.WriteLine("Client port is:" + groupEP.Port.ToString());
byte[] data = new byte[1024];
UdpClient listener = new UdpClient(2789);
while (true)
{
Console.WriteLine("Waiting for client");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine("Received Data:" + Encoding.ASCII.GetString(bytes, 0, bytes.Length));
//sending acknoledgment
string welcome = "Hello how are you from server?";
byte[] d1 = Encoding.ASCII.GetBytes(welcome);
listener.Send(d1, d1.Length, groupEP);
Console.WriteLine("Message sent to client back as acknowledgment");
}

Message not received TCP

My IP-Camera is configured to send alarm messages to my computer.
IPAddress of camera: 10.251.51.1
IPAddress of my computer: 10.251.51.136
The camera can be configured to send messages to any port on my computer.
So, I set the alarm destination to my computer's IP Address: 10.251.51.136 at port 3487.
Now, what should be done at my computer to get the message sent by the camera ?
I tried to write a TCPListener from MSDN and the code is below:
Int32 port = 3487;
IPAddress localAddr = IPAddress.Parse("10.251.51.136");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
server.Start();
// Start listening for client requests.
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
server.Start();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
But this does not seem to be working.
Or is my entire approach flawed ? Should i implement TCPListener or TCPServer instead for my scenario above?
Any pointers why?

How to test TcpListener for localhost and port number in c#

I have a code in c# which reads the data from tcp ipaddress and port number but my problem is this that i dont have any testing plateform with ipaddress and port number to test the application.My concern is this that is there any way by which i can test my code in local environmnet..
Here is my code..
public class Listener
{
private TcpListener tcpListener;
private Thread listenThread;
// Set the TcpListener on port 8081.
Int32 port = 8081;
IPAddress localAddr = IPAddress.Parse("192.168.1.3");
Byte[] bytes = new Byte[256];
public void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
public void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
// System.Windows.MessageBox.Show("socket");
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
// System.Windows.MessageBox.Show("disc");
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
String textdata = encoder.GetString(message, 0, bytesRead);
System.IO.File.AppendAllText(#"D:\ipdata.txt", textdata);
}
tcpClient.Close();
}
}
Please help me to solve this ..
Thanks in advance..
To test the TCP listening application, you obviously need to write TCP transferring one. You can write it and:
Run them simultaneously
OR
Run listener on your OS and transmitter in virtual machine. I made so and has written a post on my blog on Russian (sources are also available for download).
I think you can configure the listener to 127.0.0.1 and test logic via localhost connetcion if you have transmitting part of system
Use RESTClient chrome/firefox AddOn (http://restclient.net/) to send data to IP and Port in Intranet environment, I use this

Concurrent connections in C# socket

There are three apps run at the same time, 2 clients and 1 server. The whole system should function as following:
The client sends an serialized object to server then server receives that object as a stream, finally the another client get that stream from server and deserialize it.
This is the sender:
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("127.0.0.1", 8888);
Stream stream = tcpClient.GetStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, event); // Event is the sending object
tcpClient.Close();
Server code:
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888);
listener.Start();
Console.WriteLine("Server is running at localhost port 8888 ");
while (true)
{
Socket socket = listener.AcceptSocket();
try
{
Stream stream = new NetworkStream(socket);
// Typically there should be something to write the stream
// But I don't knwo exactly what should the stream write
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
Console.WriteLine("Disconnected: {0}", socket.RemoteEndPoint);
}
}
The receiver:
TcpClient client = new TcpClient();
// Connect the client to the localhost with port 8888
client.Connect("127.0.0.1", 8888);
Stream stream = client.GetStream();
Console.WriteLine(stream);
when I run only the sender and server, and check the server, server receives correctly the data. The problem is when I run the receiver, everything is just disconnected. So where is my problem ? Could anyone point me out ? Thanks

Categories