tcp server c# on windows, tcp client python raspberry pi - c#

I am working on my project where I have to communicate between my tcp server written in c# on windows and my client written in python on raspbian (raspberry pi). My server is working fine (tested on local machine with client in c#), but when run client data isn't sent to the server side.
c# code:
static void Main(string[] args)
{
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Krenuo sa radom...");
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Primljeno : " + dataReceived);
Console.WriteLine("Dobijena poruka na serveru : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
Console.WriteLine("\n");
client.Close();
}
listener.Stop();
python code:
def send(ctrl_cyc):
HOST, PORT = "10.93.34.41", 5000
data = ""
data += str(ctrl_cyc)
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
finally:
sock.close()
return True

I found solution... Well i think I found it.
The thing is that probably my account doesn't have rights to listen other devices in network (network configuration). I tried my solution on admin's computer and it is working, and also I put it on company's server and it is working just fine.
Here are codes if anyone needs them.
c# code:
static void Main(string[] args)
{
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(IPAddress.Any, PORT_NO);
Console.WriteLine("Krenuo sa radom...");
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Primljeno : " + dataReceived);
Console.WriteLine("Dobijena poruka na serveru : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
Console.WriteLine("\n");
client.Close();
}
listener.Stop();
}
python code:
import socket
HOST, PORT = "10.XX.XX.XX", 5000
ctrl_cyc="1234567"
data = ""
data += str(ctrl_cyc)
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n"))
data = sock.recv(1024)
print data
finally:
sock.close()

When you bind to a specific IP Address, the server only listens on the interface used for this IP Address. So if you have more then one Network adapter and you want to listen on all of them, use IpAddress.Any in the Constructor of the TcpListener.
If this is not the case, could you give us some more information:
Is the client giving any error information/exception? Have you sniffed the Traffic between client and server? Is the connection established? ...

Related

C# - Does TcpClient connection (& listening) use bandwith?

I wrote a small c# winform app that connects to my DSC alarm (via Envisalink4 by Eyez-On) and listens for TCP data sent by the alarm.
Here's an example of what I'm doing:
TcpClient tcpClient = new TcpClient(ipAddress, port);
Thread tcpThread = new Thread(o =>
{
NetworkStream clientStream = tcpClient.GetStream();
byte[] data = new byte[4096];
while (started)
{
int bytesRead = clientStream.Read(data, 0, 4096);
if (bytesRead > 0)
{
string dataString = Encoding.ASCII.GetString(responseData);
//DO SOMETHING
}
}
});
tcpThread.Start();
My question is - Other than when the alarm sends data, is any bandwidth being used while this code is waiting/listening for the server? Is there any "TCP connection overhead" while listening?
Thanks in advance!
You could use a sniffer like Wireshark to check your tcp connection

Cannot connect to a localhost. Is it client or localhost issue?

I am trying to create a thread, which keeps a listener alive at 127.0.0.1. I am using the following code to create the listener:
IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); //Localhost Ip Address
TcpListener connectionListner = new TcpListener(ipAddress, 2003);
connectedSocket = connectionListner.AcceptSocket();
connectionListner.Start();
I am facing the problem at the client-side. When I try to connect a client to the above-created localhost (separate program), I get an error.
Client Code:
class Client
{
static void Main(string[] args)
{
Console.WriteLine("client has started." + Environment.NewLine);
connectToLocalHost();
}
static void connectToLocalHost()
{
string ipaddress = "127.0.0.1";
int port = 2003;
try
{
TcpClient client = new TcpClient(ipaddress, port);
NetworkStream stream = client.GetStream();
Byte[] data = new Byte[256]; // Buffer to store the response bytes.
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (SocketException SE)
{
Console.WriteLine("Socket Error..... " + SE.StackTrace);
}
}
}
Error:
Message = "No connection could be made because the target machine
actively refused it 127.0.0.1:2003"
Maybe you need to open this port on firewall.
https://www.tomshardware.com/news/how-to-open-firewall-ports-in-windows-10,36451.html

Global Client/Server C#

How to make global access to server?
In code ,server its our local ip. On router, i create Wan Virtual server, but i cant send msg from global network.
I need to send msg from global client. And how i can save clients ip?
Thank in advance! I hope you understand my speech.
//Server
TcpListener Server = null;
try
{
Int32 port = 9595;
int MaxProc = Environment.ProcessorCount * 4;
Console.Write(GetIp()+":"+port.ToString());
Console.Write("\nCount proc * 4:"+MaxProc.ToString());
ThreadPool.SetMaxThreads(MaxProc, MaxProc);
ThreadPool.SetMinThreads(2, 2);
IPAddress LocalIp = IPAddress.Parse(GetIp());
int count = 0;
Server = new TcpListener(LocalIp,port);
Server.Start();
int max, countmax;
while(true)
{
Console.Write("\nWaiting for a connection... ");
ThreadPool.QueueUserWorkItem(ProcessMsg,Server.AcceptTcpClient());
ThreadPool.GetAvailableThreads(out max, out countmax);
Console.Write("\n Max:" + max.ToString() + "--Count:" + countmax.ToString());
count++;
Console.Write("\nConnection#"+count.ToString());
}
//Client
Int32 port = 9595;
TcpClient client = new TcpClient(server, port);
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);

TCP Server only works in localhost scheme

I can establish a TCP connection between a TCP client and TCP server in localhost, however I can't repeat the same example for a connection with different computers into the same net range (sender Windows Server 2012 x64 R2 and receiver Windows 10 x64 Pro) . The TCP Server is a C# application and the TCP client is in node.js. I have disabled both Antivirus and Windows Firewall.
//SERVER C#
void Receive() {
//tcp_Listener = new TcpListener(IPAddress.Parse("192.168.1.62"), 212);
IPAddress localAddr = IPAddress.Parse("0.0.0.0");
tcp_Listener = new TcpListener(localAddr,212);
TcpClient clientSocket = default(TcpClient);
tcp_Listener.Start();
print("Server Start");
while (mRunning)
{
// check if new connections are pending, if not, be nice and sleep 100ms
if (!tcp_Listener.Pending()){
Thread.Sleep(10);
}
else {
clientSocket = tcp_Listener.AcceptTcpClient();
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
if (dataFromClient != "") {
print ("Data from client: " + dataFromClient);
} else {
print ("Client no data");
}
clientSocket.Close();
}
}
}
//CLIENT NodeJS
var net = require('net');
var HOST = '192.168.0.136';
var PORT = 212;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('MSG SENT!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
The wireshark log about this whole connection is the following:
This is the log from TCP Client:
I have replaced for networkStream.Read (bytesFrom, 0, bytesFrom.Length)

listener.AcceptTcpClient() doesn't work in c# and works in Java

I have a socket listener application implemented in Java, and works fine
C# Code:
IPAddress serverAddress = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(serverAddress, 1234);
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
byte[] data = new byte[client.ReceiveBufferSize];
int bytesRead = stream.Read(data, 0, Convert.ToInt32(client.ReceiveBufferSize));
string request = Encoding.ASCII.GetString(data, 0, bytesRead);
Console.WriteLine(request);
}
White it works fine in Java:
ServerSocket server = new ServerSocket(1234);
Socket socket = server.accept();
In java a new client connection started, and I managed to read data. While in C# it didn't create any TcpClient at all.
Please Help!
Try replacing your TcpLister initialization with this:
TcpListener listener = new TcpListener(IPAddress.Any, 1234);
When you use "127.0.0.1" you are binding the server socket to the loopback address. Only clients on the same machine are able to communicate with servers that use the loopback IP.

Categories

Resources