TCPListener does not accept clients - c#

I'm running a TCP server in c#. The program seems to run and hold for new clients (it stop on TcpClient client = this.tcpListener.AcceptTcpClient();) waiting for new connections. However if I check the network (using the netstat command) the server is not listening, wich means is not running. I also tryied with different ports, but I guess than port 80 should be good for testing (I also tried with other ports and none of them worked). What is wrong in my code? Maybe the OS is blocking the server?
namespace TCPServer
{
class TestClass
{
static void Main(string[] args)
{
Server TCPServer = new Server();
// Display the number of command line arguments:
System.Console.WriteLine(args.Length);
}
}
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 80);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
System.Console.WriteLine("Server started");
}
//starts the tcp listener and accept connections
private void ListenForClients()
{
this.tcpListener.Start();
System.Console.WriteLine("Listener started");
while (true)
{
System.Console.WriteLine("Accepting Clients");
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
System.Console.WriteLine("Client connected");
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
//Read the data from the client
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client; //start the client
NetworkStream clientStream = tcpClient.GetStream(); //get the stream of data for network access
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
break;
}
if (bytesRead == 0) //if we receive 0 bytes
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
//Reply
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
tcpClient.Close();
}
}
}
Update:
I configure the app to get a firewall exemption. Im running in windows7. I also checked with the port 3000 and nothing listening on that port. I use the netstat output to determine if its listening or not.

Related

TCPClient runs into timeout after sending message to TCPListener

I want to create a .NET Core TCP server listening for incoming messages. I created a small class for testing purposes:
internal class TCPServer
{
private readonly TcpListener tcpListener;
public TCPServer()
{
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1234);
}
public async Task Start()
{
tcpListener.Start();
while (true)
{
TcpClient tcpClient = await tcpListener.AcceptTcpClientAsync();
NetworkStream networkStream = tcpClient.GetStream();
byte[] messageBuffer = new byte[tcpClient.ReceiveBufferSize];
int bytesRead = networkStream.Read(messageBuffer, 0, tcpClient.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(messageBuffer, 0, bytesRead);
Console.WriteLine("Message from tcp client: " + dataReceived);
}
}
}
When sending messages to that listener the client itself runs into a timeout. As you can see here
I tried to solve it by adding this line
tcpClient.Close();
but then I get this error
How can I send messages to that server without getting an error?
How do you start your test server? Have you checked the port 1234 is opened? I would recommend checking it via "telnet 127.0.0.1 1234"
If YES could you share the client's code?
If NO could you share the code starting your server?
I've tried to run it via the code above and it works pretty well to me with the telnet tool as a client
class Program
{
static void Main(string[] args)
{
TCPServer server = new TCPServer();
Console.WriteLine("Starting...");
server.Start();
Console.WriteLine("Done.");
Console.WriteLine("Press any key to quit.");
Console.ReadKey();
}
}
internal class TCPServer
{
private readonly TcpListener tcpListener;
public TCPServer()
{
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1234);
}
public async Task Start()
{
tcpListener.Start();
try
{
while (true)
{
TcpClient tcpClient = await tcpListener.AcceptTcpClientAsync();
NetworkStream networkStream = tcpClient.GetStream();
byte[] messageBuffer = new byte[tcpClient.ReceiveBufferSize];
int bytesRead = networkStream.Read(messageBuffer, 0, tcpClient.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(messageBuffer, 0, bytesRead);
Console.WriteLine("Message from tcp client: " + dataReceived);
}
}
finally
{
tcpListener.Stop();
}
}
}
The problem is that you dispose of the client socket on your loop. Once you establish a client socket, you need to keep that socket alive.
This isn't proper "server" code, but it will show you what I mean and fix your issue:
while (true)
{
var tcpClient = await tcpListener.AcceptTcpClientAsync();
while(true){
var messageBuffer = new byte[4096];
Console.WriteLine("Waiting for data...");
int bytesRead;
try
{
bytesRead = tcpClient.GetStream().Read(messageBuffer, 0, messageBuffer.Length);
}catch{ break; } // disconnected
var dataReceived = Encoding.ASCII.GetString(messageBuffer, 0, bytesRead);
Console.WriteLine($"Message from tcp client ({bytesRead} bytes): {dataReceived}");
}
}
This solution will make this work, but you can't have more than one client connected to your server at the same time. In order to do that, you need to use TPL, or worst case, create a thread for each client.
Take a look at BeginRead/EndRead to see what I mean.

Synchronization in C# networking

I have this simple tcp server class
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
Console.WriteLine("Hello");
}
private 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));
Console.WriteLine("New connexion");
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
Console.WriteLine("Got Stream");
byte[] message = new byte[4096];
int bytesRead;
Console.WriteLine("Initializing..");
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
Console.WriteLine("Reading..");
bytesRead = clientStream.Read(message, 0, 4096);
Console.WriteLine("Received something");
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
}
I simply call it in the main function like this :
Server server = new Server();
And in a separate client program I have this class
class TheClient
{
public void ConnectV2()
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
for (int i = 0; i < 20; i++)
{
byte[] buffer = encoder.GetBytes("Hello Server! " + i.ToString() + " ");
Console.WriteLine("Processing..");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
Console.WriteLine("Hello Server sent");
}
}
}
I call it in the main function like
TheClient tc = new TheClient();
tc.ConnectV2();
My problem is that the server program seems slower than the client, he don't react before the 13th, or more, message from the client :
[I can't post images because of reputation]
It reads the first dozen of messages in one go, and then reads the others one by one.
And if I make the server emit first, the client receive the message, but they both stop, like if both wait for the other to send something.
Can someone explain me this behavior ? How can I control and synchronize it ?
TCP is not message based. It provides a stream of bytes. It is your responsibility to separate messages. Also note, that you might receive only a part of a message in one Read call.
Here's a simple way to do that: Send the messages as individual lines. Possibly using StreamWriter. Receive the messages using StreamReader.ReadLine().
That way you can also use a more sane encoding such as Encoding.UTF8.
Besides that your code is actually fine and workable. It is extremely rare to see almost working TCP code on Stack Overflow. Most code is horribly broken. Congratulations.
It's because that your client AP is always sending data ,but your server AP cannot receive those data right away. So,those data stacked in buffer and then server AP receive all at once.
You can try:
Set fixed lengths when you send or receive data.
or
Receive and split data.

NullReferenceException was unhandled in TcpListener in c# [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 9 years ago.
I am trying to connect TcpListener to localhost for ip address 127.0.0.1 and port number 8081
but I'm getting an error
NullReferenceException was unhandled
Object reference not set to an instance of an object..
And here is my code ...
public class Listener
{
private TcpListener tcpListener;
private Thread listenThread;
Int32 port = 8081;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
Byte[] bytes = new Byte[256];
public void ListenForClients()
{
//getting error at this line..
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);
//mainwind.setText(encoder.GetString(message, 0, bytesRead));
//System.Windows.MessageBox.Show(encoder.GetString(message, 0, bytesRead));
// System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
}
And I am getting error at the following line of the code...
this.tcpListener.Start();
Your TcpListener is null. You need to call new on it and create an actual instance of it.
private TcpListener tcpListener;
Should probably be
private TcpListener tcpListener = new TcpListener();
You have only declared tcpListener
private TcpListener tcpListener;
It is not having any value. It is null.
You have to define it first before using it.
try
private TcpListener tcpListener = new TcpListener();

TCP port reading in C#

I have an application running at remote server which writes data (string) to its local port, I want to read this systems port by another C# application running at some other system, When i connect to this port of the remote machine I get an error that the target machine actively refused the connection.
Any suggestion will be appreciated.
I have tried this code:
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ipaddress = IPAddress.Parse("192.168.1.12");
IPAddress add = new IPAddress(ipaddress.GetAddressBytes());
EndPoint ep = new IPEndPoint(add, 7862);
sock.Connect(ep);
if (sock.Connected)
{
byte[] bytes = new byte[256];
int i = sock.Receive(bytes);
Console.WriteLine(Encoding.UTF8.GetString(bytes));
}
Here 192.168.1.12 is the IP address of the remote system, where an application is writing string continuously to port 7862. I need to read the value from that port via a C# application
I had written a program like that while ago... i copy paste it as it is, dont forget to allow "port" to the firewall and NAT so that the packet actually gets through
class Transmitter
{
public Boolean Transmit(String ip ,String port, String data){
TcpClient client = new TcpClient();
int _port = 0;
int.TryParse(port, out _port);
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(ip), _port);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(data);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
return true;
}
}
class Listener
{
private TcpListener tcpListener;
private Thread listenThread;
// Set the TcpListener on port 13000.
Int32 port = 8081;
IPAddress localAddr = IPAddress.Parse("192.168.1.3");
Byte[] bytes = new Byte[256];
MainWindow mainwind = null;
public void Server(MainWindow wind)
{
mainwind = wind;
this.tcpListener = new TcpListener(IPAddress.Any, port);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private 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);
}
}
private 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();
mainwind.setText(encoder.GetString(message, 0, bytesRead));
//System.Windows.MessageBox.Show(encoder.GetString(message, 0, bytesRead));
// System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
}

setting up a tcp server to communicate with android and kinect

I am making a dual app with android and kinect. I want to be able to send notifications to the android app from the kinect. I was told that the best way to accomplish this is to set up a simple tcp server. I tried to set it up by using the tutorial at this <link>. The tutorial however isn't descriptive enough for me and I am unable to make it work. The guy who posted it basically posted several pieces of code without any instruction about assembling them. I need someone to either walk me through setting up this server or I need a link to a detailed tutorial. I have searched the web myself for hours but I haven't found anything useful, which is why I'm asking here.
Here's what I thought he was saying to do in that tutorial:
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace TCPServerTutorial
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private 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
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
private 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);
}
}
//you'll have to find a way to pass this arg
private void SendBack(TcpClient tcpClient)
{
NetworkStream clientStream = tcpClient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0 , buffer.Length);
clientStream.Flush();
}
}
}
But that's just me. He only ever talked about one class, so it is logical to assume all his functions are in that class.
For the client code, he pretty much just gives you the code for a function (in C#, of course) which will send some bytes to an IP address (aka, the IP of the machine your server is running on). You could put this function in any C# class and call it in whatever way you wish. He has hard coded the IP address and the message to send, but these could easily be arguments passed to the function.
private void SendToServer(){
TcpClient client = new TcpClient();
//IP of the server: currently loopback, change to whatever you want
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
//Message being sent: "Hello Server!"
byte[] buffer = encoder.GetBytes("Hello Server!");
clientStream.Write(buffer, 0 , buffer.Length);
clientStream.Flush();
}

Categories

Resources