Real server-client C# program over internet - c#

Simple question, but after weeks of search no luck. I need to create a server-client program. Everything works well with localhost, but I need it over the internet. I work under Linux (Ubuntu).
Server:
public class SocketServer
{
private const int PORT_NO = 8001;
public SocketServer()
{
//---listen at the specified IP and port no.---
var listener = new TcpListener(IPAddress.Any, PORT_NO);
Console.WriteLine("Socket server started.");
listener.Start();
while (true)
{
//---incoming client connected---
var client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
var nwStream = client.GetStream();
var buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
var bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
var dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"{dataReceived}");
client.Close();
}
}
}
Client code:
public class Client
{
private const int PORT_NO = 8001;
private const string SERVER_IP = "xxx.xx.246.1";
public void Run()
{
while (true)
{
var textToSend = Console.ReadLine();
//---create a TCPClient object at the IP and port no.---
var client = new TcpClient(SERVER_IP, PORT_NO);
var nwStream = client.GetStream();
var bytesToSend = Encoding.ASCII.GetBytes(textToSend ?? string.Empty);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
}
}
}
For IP I used www.whatsmyip.org, and I got an error:
System.Net.Sockets.SocketException (0x80004005): Connection refused
What am I missing? Is there some real example, no just with localhost?

Related

Tcp connection fails on LAN

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.

Send an ASCII message

I have a "Sysmex XP-300" machine who sends data via TCP, I need to catch this data and reply with ASCII, to verify that the it was received.
The problem is, that every time the machine is connected, the code will reply "connected" non stop. I also need to reply with ASCII that my machine seems not receive. Here my code:
class Program
{
static string ack = char.ConvertFromUtf32(6);
byte[] byData = System.Text.Encoding.ASCII.GetBytes(ack);
const int PORT_NO = 3001;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
TcpServer tcpServer = new TcpServer(SERVER_IP, 3001);
tcpServer.Connected += new TcpServer.TcpServerEventDlgt(OnConnected);
tcpServer.StartListening();
Console.WriteLine("Press ENTER to exit the server.");
Console.ReadLine();
tcpServer.StopListening();
}
static void OnConnected(object sender, TcpServerEventArgs e)
{
// Handle the connection here by starting your own worker thread
// that handles communicating with the client.
Console.WriteLine("Connected.");
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(ack);// ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " );
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
}
}

TCP how do I relay the packets from my client to the server

So I am working on creating my own proxy server for my game server.
Whats happening so far is that I try to connect to my Terraria server and it says
Connecting..
Then I start my server application which accepts incoming requests on that specific IP & port and it prompts a MessageBox saying"Connected" and then the game goes from "Connecting..." to "Connecting to server..." but it gets stuck there, this is most likely because I am not redirecting the traffic from my proxy server to my server.. Right?
I've been trying to .Write() to the stream but I think I am writing to the wrong stream, do I write to the stream that accepts connections or do I create a new stream for outgoing traffic?
public partial class MainWindow : Window
{
public static IPAddress remoteAddress = IPAddress.Parse("127.0.0.1");
public TcpListener remoteServer = new TcpListener(remoteAddress, 7777);
public TcpClient client = default(TcpClient);
public TcpClient RemoteClient = new TcpClient("terraria.novux.ru", 7777);
public MainWindow()
{
InitializeComponent();
}
private void BtnListen_OnClick(object sender, RoutedEventArgs e)
{
if (StartServer())
{
client = remoteServer.AcceptTcpClient();
MessageBox.Show("Connected");
var receivedBuffer = new byte[1024];
//Should I write to this one instead?
var clientStream = client.GetStream();
var stream = RemoteClient.GetStream();
while (client.Connected)
if (client.Connected)
if (client.ReceiveBufferSize > 0)
{
receivedBuffer = new byte[1024];
stream.Write(receivedBuffer, 0, receivedBuffer.Length);
}
}
}
private bool StartServer()
{
try
{
remoteServer.Start();
MessageBox.Show("Server Started...");
return true;
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
throw;
}
}
}
A simplified implementation could look like this.
public class Program
{
public static void Main(string[] args)
{
StartTcpListener("localhost", 9000);
}
private static byte[] SendReceiveRemoteServer(string host, int port, byte[] data)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
var client = new TcpClient(host, port);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
var stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent to server: {0}", Encoding.ASCII.GetString(data));
// Receive the TcpServer.response.
// Read the first batch of the TcpServer response bytes.
var bytes = new byte[256];
var allBytes = new List<byte>();
var i = stream.Read(bytes, 0, bytes.Length);
// Loop to receive all the data sent by the client.
while (i != 0)
{
allBytes.AddRange(bytes);
bytes = new Byte[256];
i = stream.DataAvailable ? stream.Read(bytes, 0, bytes.Length) : 0;
}
Console.WriteLine("Received from server: {0}", Encoding.ASCII.GetString(data));
// Close everything.
stream.Close();
client.Close();
return allBytes.ToArray();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
return new byte[0];
}
private static void StartTcpListener(string host, int port)
{
TcpListener server = null;
try
{
var ipHostInfo = Dns.GetHostEntry(host);
var ipAddress = ipHostInfo.AddressList[0];
// TcpListener server = new TcpListener(port);
server = new TcpListener(ipAddress, port);
// Start listening for client requests.
server.Start();
// Enter the listening loop.
while (true)
{
Console.WriteLine("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
var client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
var stream = client.GetStream();
// Buffer for reading data
var bytes = new Byte[256];
var allBytes = new List<byte>();
var i = stream.Read(bytes, 0, bytes.Length);
// Loop to receive all the data sent by the client.
while (i != 0)
{
allBytes.AddRange(bytes);
bytes = new Byte[256];
i = stream.DataAvailable ? stream.Read(bytes, 0, bytes.Length) : 0;
}
if (allBytes.Count > 0)
{
Console.WriteLine("Received from client: {0}", Encoding.ASCII.GetString(allBytes.ToArray()));
var received = SendReceiveRemoteServer("localhost", 11000, allBytes.ToArray());
// Send back a response.
stream.Write(received, 0, received.Length);
Console.WriteLine("Sent to client: {0}", Encoding.ASCII.GetString(received));
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
}
}
Although improvements should be made:
make it async
make it work with multiple TcpClients at the same time

TCPlistener server-client and client-server ( send message to client from server)

All i want to do is send message to client from server. I try a lot of tutorial etc. but still can't send message from server to client.
Send from client to server is simple and have it in code. When client Send "HI" to server i want to respond Hi to client. But dunno what should i add to my code. Can someone help me with that? Please don't do it like duplicate i know there is a lot of similar topic but can't find solution.
Server code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
IPAddress ip = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener server = new TcpListener(ip, Convert.ToInt32(8555));
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
};
while (true)
{
client = server.AcceptTcpClient();
byte[] receivetBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivetBuffer, 0, receivetBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach(byte b in receivetBuffer)
{
if (b.Equals(59))
{
break;
}
else
{
msg.Append(Convert.ToChar(b).ToString());
}
}
////Resive message :
if (msg.ToString() =="HI")
{
///#EDIT 1
///// HERE Is SENDING MESSAGE TO CLIENT//////////
int byteCount = Encoding.ASCII.GetByteCount("You said HI" + 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("You said HI" + ";");
stream.Write(sendData, 0, sendData.Length);
}
}
Client code:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string serverIP = "localhost";
int port = Convert.ToInt32(8555);
TcpClient client = new TcpClient(serverIP, port);
int byteCount = Encoding.ASCII.GetByteCount("HI"+ 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("HI" + ";");
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
///////////////////////////////HERE I WANT A read message from server/
/////////////////////////////////////////////////////////////////////
stream.Close();
client.Close();
}
catch(Exception ex)
{
ex.ToString();
}
}
Try this Here is my version of client and server ,feel free to ask if any reference problem ,the client wait for server to (online) then if server is online connect with it.
Method to Connect with Server
private void Connectwithserver(ref TcpClient client)
{
try
{
//this is server ip and server listen port
server = new TcpClient("192.168.100.7", 8080);
}
catch (SocketException ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
RunBoTClient();
}
}
byte[] data = new byte[1024];
string stringData;
TcpClient client;
private void RunClient()
{
NetworkStream ns;
Connectwithserver(ref client);
while (true)
{
ns = client.GetStream();
//old
// ns.ReadTimeout = 50000;
//old
ns.ReadTimeout = 50000;
ns.WriteTimeout = 50000;
int recv = default(int);
try
{
recv = ns.Read(data, 0, data.Length);
}
catch (Exception ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
//try to reconnect if server not respond
RunClient();
}
//READ SERVER RESPONSE/MESSAGE
stringData = Encoding.ASCII.GetString(data, 0, recv);
}
}
Server
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---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);
//IF YOU WANT TO WRITE BACK TO CLIENT USE
string yourmessage = console.ReadLine();
Byte[] sendBytes = Encoding.ASCII.GetBytes(yourmessage);
//---write back the text to the client---
Console.WriteLine("Sending back : " + yourmessage );
nwStream.Write(sendBytes, 0, sendBytes.Length);
client.Close();
}
listener.Stop();

TcpListener doesn't detect connection

I have been doing a client-server application in these days. I made a server part based on examples to launch a TcpListener and It seems to be working well.
However, It's not able to detect client connections, while the client says that It connected to the given ip and port.
Here is my code for the server side:
internal static void RunServer()
{
// Create a TCP/IP (IPv4) socket and listen for incoming connections.
ServerLogger.LogStatus("Starting listener...");
listener = new TcpListener(IPAddress.Any, Server.PORT + 2);
listener.Start();
ServerLogger.LogStatus("Starting thread listener...");
tlisten = new Thread(Listen);
tlisten.Start();
ServerLogger.LogStatus("Starting receiver...");
treceiver = new Thread(Receiver);
treceiver.Start();
ServerLogger.LogStatus("All done!");
}
internal static void Listen() // Listen to incoming connections.
{
while (running)
{
ServerLogger.LogStatus("Waiting for a connecion....");
TcpClient tcpClient = listener.AcceptTcpClient();
// The below code never runs on client connection.
ServerLogger.LogStatus("Accepting and Creating cert!");
// Create a new certification
byte[] serverCertificatebyte = Certificate.CreateSelfSignCertificatePfx("Test" + IP + RandomString(5),
new DateTime(2015, 12, 26),
new DateTime(DateTime.Today.Year, DateTime.Today.Month + 1, DateTime.Today.Day), RandomString(20));
ServerLogger.LogStatus("Created certificate!");
X509Certificate serverCertificate = new X509Certificate(serverCertificatebyte);
tcpclientbytecerts[tcpClient] = serverCertificatebyte;
tcpclientcerts[tcpClient] = serverCertificate;
ServerLogger.LogInfo("Sending Certificate!");
// Send SSL certification in bytes
tcpClient.GetStream().Write(serverCertificatebyte, 0, serverCertificatebyte.Length);
ServerLogger.LogInfo("Certificate sent to the client!");
Logger.Log(serverCertificatebyte.ToString());
// process it
ServerLogger.LogInfo("Processing");
ProcessClient(tcpClient, serverCertificate);
ServerLogger.LogInfo("Processed!");
}
}
Client side:
private SSL(string ip, int port)
{
UnityEngine.Debug.Log("Test");
if (!PrivacyHelper.IsInvocationAllowed())
{
Terminate();
}
UnityEngine.Debug.Log("Test2 " + ip + " - " + port);
UnityEngine.Debug.Log("Test3 " + IsLocalIpAddress(ip));
client = new TcpClient(ip, port);
//client.Connect(ip, port);
UnityEngine.Debug.Log("Test4 " + client.Connected); // <- This is true
var stream = client.GetStream();
UnityEngine.Debug.Log("Test5");
Byte[] cert = new Byte[65535];
UnityEngine.Debug.Log("Test6");
Int32 bytes = stream.Read(cert, 0, cert.Length);
UnityEngine.Debug.Log("Test7");
byte[] intBytes = BitConverter.GetBytes(bytes);
UnityEngine.Debug.Log("Test8");
if (BitConverter.IsLittleEndian) { Array.Reverse(intBytes);}
UnityEngine.Debug.Log("Test9");
byte[] result = intBytes;
UnityEngine.Debug.Log("Cert: " + result);
certificate1 = new X509Certificate2(result);
//client.GetStream().Read()
}
The client seems to be able to connect, It even returns true and says that It's connected. The server side doesn't detect It though. Any ideas?

Categories