Best way of organising connection between server and clients in LAN? - c#

We have an android app that on one particular device acts like a server. And all the other devices act like clients.
Server is starting to listen for incoming tcp connections in while loop. When connection request received it fires an event, so the user of this class can handle request and then call WriteData method of the MyTcpServer class to respond to income request. Then networkStream of connected client is closed and new iteration of loop is started.
Is it a good practice to receive incoming requests in a while loop and then to close it after sending data to client?
A server and clients use the same class listed below:
public class MyTcpServer
{
#region Fields
TcpListener listener;
TcpClient client;
#endregion
#region Properties
public bool IsRunning { get; private set; }
#endregion
#region Protected methods
protected static byte[] StringToBytes(string input)
{
return Encoding.UTF8.GetBytes (input);
}
#endregion
#region Public methods
public void Start(string SERVER_IP, int PORT_NO)
{
if (IsRunning)
return;
IsRunning = true;
Task.Run (() => {
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse (SERVER_IP);
listener = new TcpListener (localAdd, PORT_NO);
Console.WriteLine ("Listening...");
listener.Start ();
while (true) {
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);
var ip = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString ();
Array.Clear (buffer, 0, buffer.Length);
Console.WriteLine ("[" + DateTime.Now.ToString ("HH:mm:ss") + "] Received : " + dataReceived);
DataReceived?.Invoke (this, new Data () {Stream = nwStream, Message = dataReceived,
IP = ip
});
nwStream.Close();
}
});
}
public void WriteData(NetworkStream nwStream, byte[] responseData)
{
try {
nwStream.Write (responseData, 0, responseData.Length);
} catch (Exception e) {
Console.WriteLine (e.ToString ());
}
}
public void WriteData(string ip, int port, byte[] data)
{
try {
var client = new TcpClient (ip, port);
var nwstream = client.GetStream ();
nwstream.Write (data, 0, data.Length);
nwstream.Close ();
} catch (Exception e) {
Console.WriteLine (e.ToString ());
}
}
public void Stop()
{
if (client != null)
client.Close ();
listener.Stop ();
IsRunning = false;
}
#endregion
public event EventHandler<Data> DataReceived;
public class Data
{
public NetworkStream Stream {get;set;}
public string Message {get;set;}
public string IP {get;set;}
}
}

Related

Netcore Socket Server Not Closing

Hi All I'm developing a quite simple Socket Server on .NetCore. This server must allow multiple clients and start reading from them while it's not canceled.
This is the code of it:
public class ClientHandler
{
public ClientHandler(Socket workSocket, int bufferSize)
{
WorkSocket = workSocket;
BufferSize = bufferSize;
receiveBuffer = new byte[BufferSize];
currentBuffer = new byte[0];
}
public Socket WorkSocket { get; }
// Size of receive buffer.
public int BufferSize { get; }
// Receive buffer.
public byte[] receiveBuffer { get; set; }
// Received data.
public byte[] currentBuffer { get; set; }
}
public class MyServer
{
public MyServer(string ipAddress, int port,
IProtocolParser parser, CancellationToken token, ILogger logger)
{
_ipAddress = ipAddress;
_port = port;
InternalCts = new CancellationTokenSource();
_token = InternalCts.Token;
_parser = parser;
_logger = logger.ForContext(GetType());
}
private const int BUFFER_SIZE = 1024;
private readonly IProtocolParser _parser;
private readonly ILogger _logger;
private readonly int _port;
private readonly string _ipAddress;
private readonly CancellationToken _token;
private readonly ManualResetEvent _allDone = new ManualResetEvent(false);
private CancellationTokenSource InternalCts { get; set; }
private Socket Server { get; set; }
public void Start()
{
try
{
var ipAddress = IPAddress.Parse(_ipAddress);
var endpoint = new IPEndPoint(ipAddress, _port);
_logger.Debug("Creating Socket Server On {ipAddress}:{port}", _ipAddress, _port);
Server = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Server.Bind(endpoint);
Server.Listen(10);
while(!_token.IsCancellationRequested)
{
_allDone.Reset();
_logger.Debug("Waiting For Client");
Server.BeginAccept(AcceptCallback, Server);
_logger.Debug("Waiting One!");
_allDone.WaitOne();
_logger.Debug("Begin Accept Finished");
}
_logger.Debug("Task Finished!");
return;
}
catch (Exception e)
{
_logger.Error("error");
}
}
private void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
_allDone.Set();
// Get the socket that handles the client request.
var listener = (Socket)ar.AsyncState;
var handler = listener.EndAccept(ar);
// Create the state object.
var client = new ClientHandler(handler, BUFFER_SIZE);
handler.BeginReceive(client.receiveBuffer, 0, client.BufferSize, 0,
new AsyncCallback(ReadCallback), client);
}
private void ReadCallback(IAsyncResult ar)
{
// Retrieve the state object and the handler socket
// from the asynchronous state object.
var client = (ClientHandler)ar.AsyncState;
var handler = client.WorkSocket;
// Read data from the client socket.
var bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
client.currentBuffer = ArrayExtensions.Combine(
client.currentBuffer, client.receiveBuffer.SubArray(0, bytesRead));
var (message, newBuffer) = _parser.UnpackMessage(client.currentBuffer);
if (!string.IsNullOrEmpty(message))
{
_logger.Debug("New Message Received: {message}", message);
}
client.currentBuffer = newBuffer;
}
if (!_token.IsCancellationRequested)
{
// Not all data received. Get more.
handler.BeginReceive(client.receiveBuffer, 0, client.BufferSize, 0,
new AsyncCallback(ReadCallback), client);
}
}
public void Stop()
{
InternalCts.Cancel();
_logger.Debug("Stopping Server...");
_logger.Debug("Closing Socket...");
Server.Close();
_allDone.Set();
_logger.Debug("Socket Closed!");
}
}
And this is the main program:
static void Main(string[] args)
{
var parser = new VenomOEMProtocolParser();
var cts = new CancellationTokenSource();
var logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.WriteTo.Console().CreateLogger();
var venomOem = new VenomOEM("192.168.0.107", 100, parser, cts.Token, logger);
AppDomain.CurrentDomain.ProcessExit += (s, e) =>
{
venomOem.Stop();
};
Console.CancelKeyPress += delegate
{
venomOem.Stop();
};
try
{
venomOem.Start();
logger.Debug("FINISHED!");
}
catch (OperationCanceledException oce)
{
logger.Debug(oce, "Operation Canceled Exception");
}
catch (Exception e)
{
logger.Error(e, "Unexpected Exception!");
}
}
As you can see I start the sever and stop it when Ctrl+C keys are pressed on the console app and the stop method is excecuted but somehow the application freezes and doesn't close. I think that it's something related to the reset events but cannot find the problem.
Any suggestion?
Thanks!

Make the server to listening always (Simple server)

I have a Server class that receives .txt file from client class.
My problem: My server only receives the first .txt file but after that the client can't send anymore, how can I convert my Server class such that the server will always will listening to new files?
Here is the server:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string rd;
byte[] b1;
string v;
int m=20;//number of byts
TcpListener list;
TcpClient client;
int port = 8100;//5050
int port1 = 8100;//5055
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
private void button1_Click(object sender, EventArgs e)//browse button
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
// while (true)
//try
// {
list = new TcpListener(localAddr, port1);
list.Start();
Thread incoming_connection = new Thread(ic);
incoming_connection.Start();
/*
}catch(Exception exc)
{
Console.Write(exc);
break;
}*/
}
}
private void ic()
{
client = list.AcceptTcpClient();
Stream s = client.GetStream();
b1 = new byte[m];
s.Read(b1,0, b1.Length);
MessageBox.Show("pathh "+textBox1.Text);
File.WriteAllBytes(textBox1.Text+"\\flag.txt", b1);// the left side us the name of the written file
//list.Stop();
//client.Close();
// label1.Text = "File Received......";
}
private void Form2_Load(object sender, EventArgs e)
{
list = new TcpListener(localAddr, port);
// TcpListener list = new TcpListener(port);
list.Start();
TcpClient client = list.AcceptTcpClient();
MessageBox.Show("Client trying to connect");
StreamReader sr = new StreamReader(client.GetStream());
rd = sr.ReadLine();
v = rd.Substring(rd.LastIndexOf('.') + 1);
m = int.Parse(v);
// list.Stop();
// client.Close();
}
}
Related-1
Realted-2
First, You need someone to send text, and someone to receive text
Let's begin with the Sender, let's call it Server
public class Server
{
//This is where the receiver connection will be stored
public TcpClient ClientConnection { get; set; }
public int Port { get; set; }
public string Host { get; set; }
public TcpListener Listener;
public Server(int port,string host)
{
this.Port = port;
this.Host = host;
}
public void Start()
{
this.Listener = new TcpListener(IPAddress.Parse(Host), Port);
TryConnect();
}
public void TryConnect()
{
//You can use thread
Task.Factory.StartNew(AcceptTheClientConnection, TaskCreationOptions.LongRunning);
}
public void AcceptTheClientConnection()
{
ClientConnection = this.Listener.AcceptTcpClient();
}
public void SendText(string text)
{
if (ClientConnection != null)
{
try
{
var buffer = System.Text.Encoding.Default.GetBytes(text);
ClientConnection.Client.Send(buffer, SocketFlags.None);
}
catch(Exception e)
{
ClientConnection = null;
TryConnect();
}
}
else throw new InvalidOperationException("You must connect to client first");
}
}
Now The Receiver is a TcpClient, this Receiver will open the connection by providing it with the Sender IP Address and the port. The Receiver will run two threads after successfully connecting to the Sender. The first thread will keep listening for new files, adding the received file buffer to the queue. The second one will process these buffers, here you can put your own logic.
public class Client
{
public int SenderPort { get; set; }
public byte[] Buffer { get; set; }
public string SenderHost { get; set; }
public TcpClient SenderConnection;
public Queue<byte[]> ReceivedTextFiles;
public Client(int senderPort, string senderHost)
{
this.SenderPort = senderPort;
this.SenderHost = senderHost;
ReceivedTextFiles = new Queue<byte[]>();
}
public Task Connect()
{
return Task.Factory.StartNew(() =>
{
SenderConnection = new TcpClient();
SenderConnection.Connect(SenderHost, SenderPort);
Thread t = new Thread(Recieve);
Thread t2 = new Thread(ProcessTextFiles);
t.Start();
t2.Start();
});
}
public void Recieve()
{
while (true)
{
Thread.Sleep(500);
if (SenderConnection.Available > 0)
{
lock (Buffer)
{
Buffer = new byte[SenderConnection.Available];
int receivedBytes = SenderConnection.Client.Receive(Buffer);
if (receivedBytes > 0)
{
lock (ReceivedTextFiles)
{
ReceivedTextFiles.Enqueue(Buffer);
Buffer = null;
}
}
}
}
}
}
public void ProcessTextFiles()
{
while (true)
{
byte[] textFile = null;
lock (ReceivedTextFiles)
{
//We have buffers to process, get one, and remove it from the queue
if (ReceivedTextFiles.Count > 0)
{
textFile = ReceivedTextFiles.Dequeue();
}
}
//Process the buffer
var textFileContent = System.Text.Encoding.Default.GetString(textFile);
//Do whatever you want
Thread.Sleep(1500);
}
}
}
This is the general idea behind sockets, and how to send and receive data in the network. Keep in mind, this solution is tailored for your purpose, which will accept only one connection. And this is not the best solution, but due to your requirement; I tried to make it as simple as possible. Also please note that you can use Threads, or Tasks It depends on the context. I will let you chose who to consume these two classes as you want. You can edit these two classes of course.

Improving TCP forwarder using Socket in C#

I have Implemented a simple TCP forwarder which is connected to a backend server. This server is set on http://localhost:5000 and this TCP forwarder is listening to http://localhost:5001. Using another machine to generate load using wrk which is a HTTP benchmarking tool to generator load, I have 2 different results. When I send the load directly to the service which is based on asp.net core web api on the kestrel more than 230K requests/second are handled but when I send the load to this TCP forwarder 83Krequest/second can be handled. Here is the code:
using System;
using System.Net;
using System.Net.Sockets;
namespace BrunoGarcia.Net
{
static void Main(string[] args)
{
new TcpForwarderSlim().Start(
new IPEndPoint(IPAddress.Parse(args[0]), int.Parse(args[1])),
new IPEndPoint(IPAddress.Parse(args[2]), int.Parse(args[3])));
}
public class TcpForwarderSlim
{
private readonly Socket _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public void Start(IPEndPoint local, IPEndPoint remote)
{
_mainSocket.Bind(local);
_mainSocket.Listen(10);
while (true)
{
var source = _mainSocket.Accept();
var destination = new TcpForwarderSlim();
var state = new State(source, destination._mainSocket);
destination.Connect(remote, source);
source.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
}
private void Connect(EndPoint remoteEndpoint, Socket destination)
{
var state = new State(_mainSocket, destination);
_mainSocket.Connect(remoteEndpoint);
_mainSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, OnDataReceive, state);
}
private static void OnDataReceive(IAsyncResult result)
{
var state = (State)result.AsyncState;
try
{
var bytesRead = state.SourceSocket.EndReceive(result);
if (bytesRead > 0)
{
state.DestinationSocket.Send(state.Buffer, bytesRead, SocketFlags.None);
state.SourceSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
}
catch
{
state.DestinationSocket.Close();
state.SourceSocket.Close();
}
}
private class State
{
public Socket SourceSocket { get; private set; }
public Socket DestinationSocket { get; private set; }
public byte[] Buffer { get; private set; }
public State(Socket source, Socket destination)
{
SourceSocket = source;
DestinationSocket = destination;
Buffer = new byte[8192];
}
}
}
}
What is the problem do you think?! How can I improve the result when I use TCP forwarder?!Or is there a better way to make a tunnel or a forwarder to listen to a port and send the TCP requests to one of 2 or more back end service?!
You do not start listening for a more data till state.DestinationSocket.Send completes. You can start listening for more data as soon as you start processing the Send, the order of multiple BeginSend calls is preserved so if you switched to that it would allow you to start processing the next request before the previous one finished.
Important note! You will now need to create a new buffer (or use a pool of buffers) for each new BeginReceive request. Below is untested code but hopefully is close enough to get you on the right path.
public class TcpForwarderSlim
{
private readonly Socket _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public void Start(IPEndPoint local, IPEndPoint remote)
{
_mainSocket.Bind(local);
_mainSocket.Listen(10);
while (true)
{
var source = _mainSocket.Accept();
var destination = new TcpForwarderSlim();
var state = new State(source, destination._mainSocket);
destination.Connect(remote, source);
source.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
}
private void Connect(EndPoint remoteEndpoint, Socket destination)
{
var state = new State(_mainSocket, destination);
_mainSocket.Connect(remoteEndpoint);
_mainSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, OnDataReceive, state);
}
private static void OnDataReceive(IAsyncResult result)
{
var state = (State)result.AsyncState;
try
{
var bytesRead = state.SourceSocket.EndReceive(result);
if (bytesRead > 0)
{
//Start an asyncronous send.
var sendAr = state.DestinationSocket.BeginSend(state.Buffer, 0, bytesRead, SocketFlags.None,null,null);
//Get or create a new buffer for the state object.
var oldBuffer = state.ReplaceBuffer();
state.SourceSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
//Wait for the send to finish.
state.DestinationSocket.EndSend(sendAr);
//Return byte[] to the pool.
state.AddBufferToPool(oldBuffer);
}
}
catch
{
state.DestinationSocket.Close();
state.SourceSocket.Close();
}
}
private class State
{
private readonly ConcurrentBag<byte[]> _bufferPool = new ConcurrentBag<byte[]>();
private readonly int _bufferSize;
public Socket SourceSocket { get; private set; }
public Socket DestinationSocket { get; private set; }
public byte[] Buffer { get; private set; }
public State(Socket source, Socket destination)
{
SourceSocket = source;
DestinationSocket = destination;
_bufferSize = Math.Min(SourceSocket.ReceiveBufferSize, DestinationSocket.SendBufferSize);
Buffer = new byte[_bufferSize];
}
/// <summary>
/// Replaces the buffer in the state object.
/// </summary>
/// <returns>The previous buffer.</returns>
public byte[] ReplaceBuffer()
{
byte[] newBuffer;
if (!_bufferPool.TryTake(out newBuffer))
{
newBuffer = new byte[_bufferSize];
}
var oldBuffer = Buffer;
Buffer = newBuffer;
return oldBuffer;
}
public void AddBufferToPool(byte[] buffer)
{
_bufferPool.Add(buffer);
}
}
}

UDP not receiving updated values

My udp class is not receiving the updated value from the stream. Device sends data continuously and when any alarm activated it add the code in stream and sends the updated value but my class is not receiving the updated value unless I restart the program.
here is my UDPListener class.
public class
{
public static int PORT_NUMBER { get; set; }
public string IpAddress { get; set; }
private readonly UdpClient udp;
public event Action<object, EventArgs> msgChanged;
IAsyncResult ar_ = null;
public UDPListener(string ipaddr, int port)
{
IpAddress = ipaddr;
PORT_NUMBER = port;
udp = new UdpClient(PORT_NUMBER);
Start();
}
public void Start()
{
StartListening();
}
public void Stop()
{
try
{
udp.Close();
}
catch { /* not necessary */ }
}
private void StartListening()
{
ar_ = udp.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
try
{
Thread.Sleep(150);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(IpAddress), PORT_NUMBER);
byte[] bytes = udp.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
//raise event..
if (message.StartsWith("S"))
if (msgChanged != null)
msgChanged(message, EventArgs.Empty);
}
catch (Exception ex)
{
Debug.WriteLine("Error in UDPListner..." + ex.Message);
}
finally
{
StartListening();
}
}
}
Now what is happening when the program starts it will receive data "S0000.." but when alarm raises data changes to "S8000..etc" but this class continuously receiving the same "S000.." data unless I restart the class.
When I run the udp listener in while loop its works perfectly fine, it receives the updated stream and changes when alarm goes off.
here is the code for while loop udp.
while (!StopRunning)
{
Thread.Sleep(150);
udp = new UdpClient(PORT_NUMBER, AddressFamily.InterNetwork);
var ep = default(IPEndPoint);
var data = udp.Receive(ref ep);
udp.Close();
string msg = Encoding.ASCII.GetString(data);
if (msgChanged != null)
msgChanged(msg, EventArgs.Empty);
}
But I cannot make use of while loop because I have to fit this program in window service.
The main difference in your UDPListener and while loop is that in loop you are creating udp variable each time you are connecting to the UDP:
udp = new UdpClient(PORT_NUMBER, AddressFamily.InterNetwork);
In Receive(IAsyncResult ar) you only connect with the same client, so you still have the same data.
I think that you can rewrite your class something like this:
private void StartListening()
{
udp = new UdpClient(PORT_NUMBER, AddressFamily.InterNetwork);
ar_ = udp.BeginReceive(Receive, new object());
}
Make sure that you're disposing the udp connection after receive with Close() method:
byte[] bytes = udp.EndReceive(ar, ref ip);
udp.Close();

How to fix "a connection attempt failed because the connected party did not properly respond after a period of time ..." error?

I'm making a game in C# and I want to display the progress (movements and so on) of opponent. So I send events in game via TCP protocol to opponent.
I've already tried my application on localhost and it works but when I try to use my external address in order to communicate over the internet I get the error below in class TcpInformer.Connect():
a connection attempt failed because the connected party did not properly respond after a
period of time, or established connection failed because connected host has failed to
respond (my external IP address):(port)
I thought the problem was that I was behind NAT. But I've already set up portforwarding for port 49731 on IP 10.0.0.1 and nothing changed.
My second guess was Windows firewall but even when I stopped the firewall my app didn't start working.
My code for connecting of the two PCs is:
TcpInformer peer;
TcpHost server;
public void PrepareConnection() // for server (host)
{
playerType = PlayerType.One;
server = new TcpHost(form, this);
server.Start("10.0.0.1", 49731);
}
public void PrepareConnection2() // for client
{
playerType = PlayerType.Two;
peer = new TcpInformer(form, this);
peer.Connect("MY EXTERNAL IP", 49731);
}
// classes TcpHost and TcpInformer
public interface ITcpCommunication
{
#region Operations (3) 
void ReadData();
void SendData(byte[] message);
void SendData(byte[] message, int size);
#endregion Operations 
}
public class TcpInformer : ITcpCommunication
{
#region Fields (9) 
private NetworkStream con_ns;
private TcpClient con_server;
private bool connected;
private Fmain form;
private SecondPlayer player;
private int port;
private string server;
private string stringData;
#endregion Fields 
#region Delegates and Events (1)
// Events (1) 
public event SimulationEventHandler ReadEvent;
#endregion Delegates and Events 
#region Constructors (1) 
public TcpInformer(Fmain form, SecondPlayer player)
{
this.form = form;
connected = false;
this.player = player;
}
#endregion Constructors 
#region Methods (6) 
// Public Methods (5) 
///
///
///
/// e.g., server = "127.0.0.1"
/// e.g., port = 9050
public void Connect(string server, int port)
{
this.port = port;
this.server = server;
connected = true;
try
{
con_server = new TcpClient(this.server, this.port);
}
catch (SocketException ex)
{
connected = false;
MessageBox.Show("Unable to connect to server" + ex.Message);
return;
}
con_ns = con_server.GetStream();
}
public void Disconnect()
{
form.Debug("Disconnecting from server...", "Player2Net");
con_ns.Close();
con_server.Close();
}
public void ReadData()
{
if (con_ns != null)
{
if (con_ns.DataAvailable)
{
byte[] data = new byte[1200];
int received = con_ns.Read(data, 0, data.Length);
player.ProcessReceivedData(data, received);
}
}
else
{
form.Debug("Warning: con_ns is not inicialized.","player2");
}
}
public void SendData(byte[] message)
{
con_ns.Write(message, 0, message.Length);
con_ns.Flush();
}
public void SendData(byte[] message, int size)
{
if (con_ns != null)
{
con_ns.Write(message, 0, size);
}
}
// Private Methods (1) 
private void Debug(string message)
{
form.Debug("Connected to: " + server + "port: " + port.ToString() + ": " + message, "Player2Net");
}
#endregion Methods 
}
public class TcpHost : ITcpCommunication
{
#region Fields (9) 
private ASCIIEncoding enc;
private Fmain form;
private TcpListener listener;
private SecondPlayer player;
private int port;
private Socket s;
private string server;
private bool state;
#endregion Fields 
#region Delegates and Events (1)
// Events (1) 
public event SimulationEventHandler ReadEvent;
#endregion Delegates and Events 
#region Constructors (1) 
public TcpHost(Fmain form, SecondPlayer player)
{
this.player = player;
this.form = form;
state = false;
enc = new ASCIIEncoding();
}
#endregion Constructors 
#region Methods (5) 
// Public Methods (5) 
public void Close()
{
state = false;
s.Close();
listener.Stop();
}
public void ReadData()
{
if (state == true)
{
if (s.Available > 0) // if there's any data
{
byte[] data = new byte[1200];
int received = s.Receive(data);
player.ProcessReceivedData(data, received);
}
}
}
public void SendData(byte[] message)
{
if (state == true)
{
s.Send(message);
}
}
public void SendData(byte[] message, int size)
{
if (state == true)
{
s.Send(message, size, SocketFlags.None);
}
}
public void Start(string p_ipAddress, int listenPort)
{
//IPAddress ipAddress = IPAddress.Loopback
IPAddress ipAddress = IPAddress.Parse(p_ipAddress);
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, listenPort);
//listener = new TcpListener(ipAddress, listenPort);
listener = new TcpListener(ipLocalEndPoint);
server = "[provider]";
port = listenPort;
listener.Start();
form.Debug("Server is running", "Player1Net");
form.Debug("Listening on port " + listenPort, "Player1Net");
form.Debug("Waiting for connections...", "Player1Net");
s = listener.AcceptSocket();
form.Debug("Connection accepted from " + s.RemoteEndPoint, "Player1Net");
state = true;
}
#endregion Methods 
}
Is there a way how to check what is wrong?
Help is much appreciated!
I found out what was the problem. I was listening on 10.0.0.1 and trying to reach my external IP (second instance of my program) which is impossible on a computer with one connection to the internet.
I also faced the same problem in AWS VPN.
I changed the proxy.company.com (external ip) to 10.0.0.5.
And it works now.

Categories