TCP Server only works in localhost scheme - c#

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)

Related

How can I listen to incoming query to SQL Server with a TCP Server built with ASP.NET Core

I created a TCP Server and TCP Client for testing with ASP.NET Core.
This is my TCP Server:
public class TCPServer
{
public static void Main(string[] args)
{
// Start the server
TCPHelper.StartServer(5678);
TCPHelper.Listen(); // Start listening.
}
}
Here are my functions in the TCP Helper I use:
class TCPHelper
{
private static TcpListener listener { get; set; }
private static bool accept { get; set; } = false;
public static void StartServer(int port)
{
IPAddress localAdd = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(localAdd, port);
Console.WriteLine("Listening...");
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
Console.WriteLine($"Server started. Listening to TCP clients at 127.0.0.1:{port}");
}
public static void Listen()
{
if (listener != null && accept)
{
// Continue listening.
while (true)
{
Console.WriteLine("Waiting for client...");
var clientTask = listener.AcceptTcpClientAsync(); // Get the client
if (clientTask.Result != null)
{
Console.WriteLine("Client connected. Waiting for data.");
var client = clientTask.Result;
byte[] buffer = new byte[1024];
client.GetStream().Read(buffer, 0, buffer.Length);
var message = Encoding.UTF8.GetString(buffer);
}
}
}
}
}
Finally, this is the TCP CLient side and my main problem is actually in this part:
public class TCPClient
{
static void Main(string[] args)
{
//I am trying to connect to Tcp Server with connection string.
var conn_string= "server=tcp:127.0.0.1, 5678;Initial Catalog=mydb;Persist Security Info=False;User ID=userid;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=120;";
using (SqlConnection connection = new SqlConnection(conn_string))
{
connection.Open();
}
}
}
The first part of the Connection String is the information of my TCP Server that I broadcast, I want to specify the connection string in this way and connect to SQL Server as if my customers are connecting to my TCP Server and then read the SQL queries they will make.
So I want to use TCP Server as a layer between the client and SQL Server, but my clients must think they are connecting to SQL Server.
When I run this code, I get an error like this:
System.Data.SqlClient.SqlException: 'A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The specified network name is no longer available.)'
And in the terminal of my TCP Server it reads something like:
I would be very grateful for any help

C# - Cannot connect my Socket Server

Good afternoon dear community,
I am currently working on a Arduino + Unity project where I am supposed to build an Arduino control through Unity. For that, I have set my Arduino and connected to wifi.
I built a Socket Server with C#. The problem is that: I am able to connect to this Socket Server through a Node.js Socket Client, however to check if my Arduino setup is broken, I have built a Node.js Socket Server and was able to connect my Node.js Socket server succesfully through Arduino. (The only reason I am using Node.js here is that because I am more fluent on that platform so I am able to check what is wrong, so final project does not have any Node.js.) So;
Node.js Client -> Unity C# Server (Works)
Arduino Client -> Node.js Server (Works) (Below is Arduino output)
AT+CIPSTART=3,"TCP","192.168.1.67",1234
OK
Linked
Arduino Client -> Unity C# Server (Does not work) (Below is Arduino output)
AT+CIPSTART=3,"TCP","192.168.1.67",1234
ERROR
Unlink
Below I am putting my all C#, Node.js and Arduino codes. I don`t think that there is an Arduino hardware issue here, but don·t understand why I cannot connect my
Unity Socket Server.
using System;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using UnityEngine;
public class SocketScript : MonoBehaviour {
Thread tcpListenerThread;
void Start()
{
tcpListenerThread = new Thread(() => ListenForMessages(1234));
tcpListenerThread.Start();
}
public void ListenForMessages(int port)
{
TcpListener server = null;
try
{
IPAddress localAddr = IPAddress.Parse("192.168.1.67");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new byte[256];
String data = null;
while(true)
{
Debug.Log("Waiting for connection.");
using (TcpClient client = server.AcceptTcpClient())
{
Debug.Log("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
// As long as there is something in the stream:
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);
Debug.Log(String.Format("Received: {0}", data));
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Debug.Log(String.Format("Sent: {0}", data));
}
}
}
} catch (SocketException e)
{
Debug.LogError(String.Format("SocketException: {0}", e));
} finally
{
server.Stop();
}
}
}
Node.js Client:
var net = require('net');
var HOST = '192.168.1.67';
var PORT = 1234;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('Client 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('Hello World!');
});
client.on('data', function(data) {
console.log('Client received: ' + data);
if (data.toString().endsWith('exit')) {
client.destroy();
}
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Client closed');
});
client.on('error', function(err) {
console.error(err);
});
Node.js Server:
var net = require('net');
// Configuration parameters
var HOST = '192.168.1.67';
var PORT = 1234;
// Create Server instance
var server = net.createServer(onClientConnected);
server.listen(PORT, HOST, function() {
console.log('server listening on %j', server.address());
});
function onClientConnected(sock) {
var remoteAddress = sock.remoteAddress + ':' + sock.remotePort;
console.log('new client connected: %s', remoteAddress);
sock.on('data', function(data) {
console.log('%s Says: %s', remoteAddress, data);
sock.write(data);
sock.write(' exit');
});
sock.on('close', function () {
console.log('connection from %s closed', remoteAddress);
});
sock.on('error', function (err) {
console.log('Connection %s error: %s', remoteAddress, err.message);
});
};

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

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? ...

Android Server connect to C# Client

I turned on my mobile's hotspot and connected my computer to the hotspot
and used this code to create server but InetAddress became "/0.0.0.0":
ServerSocket ss = null;
try {
ss= new ServerSocket(4444);
//texto.append("\n"+ss.getInetAddress());
Log.d("TcpServer", ss.getInetAddress()+"");
log= ss.getInetAddress().toString();
//ss.setSoTimeout(10000);
//accept connections
Socket s = ss.accept();
Log.i("TcpServer", "Receiving");
//texto.append("\n"+"Receiving");
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
//BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//receive a message
Log.i("TcpServer", in.readLine());
final String incomingMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpServer", "received: " + incomingMsg);
runOnUiThread(new Runnable() {
public void run() {
// texto.append("received: " + incomingMsg);
}
});
s.close();
Yes. If you just create a socket, the default is to listen on all network devices/all assigned IP addresses, which is reflected by listening on IP 0.0.0.0.

Get client IP from UDP packages received with UdpClient

I am developing an action multiplayer game with the help of the System.Net.Sockets.UdpClient class.
It's for two players, so one should open a server and wait for incoming connections. The other player inputs the host IP and tries to send a "ping", to make sure a connection is possible and there is an open server. The host then responds with a "pong".
Once the game is running, both have to send udp messages to each other, so they both need the opponents ip address.
Of course the server could also input the clients IP, but that seems unneccessary to me.
How can I get the clients IP from the udp package when the "ping" message is received?
Here is my receiving code (server waiting for ping):
private void ListenForPing()
{
while (!closeEverything)
{
var deserializer = new ASCIIEncoding();
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] recData = udp.Receive(ref anyIP);
string ping = deserializer.GetString(recData);
if (ping == "ping")
{
Console.WriteLine("Ping received.");
InvokePingReceiveEvent();
}
}
}
In your example, when a client connects, the anyIP IPEndPoint object will contain the address and port of the client connection.
private void ListenForPing()
{
while (!closeEverything)
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] recData = udp.Receive(ref anyIP);
string ping = Encoding.ASCII.GetString(recData);
if (ping == "ping")
{
Console.WriteLine("Ping received.");
Console.WriteLine("Ping was sent from " + anyIP.Address.ToString() +
" on their port number " + anyIP.Port.ToString());
InvokePingReceiveEvent();
}
}
}
http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.receive.aspx

Categories

Resources