Reverse connection error - c#

I'm trying to make a reverse connection, but nothing happens
system only tries to connect infinitely
client code :
private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public static TcpClient client;
private const int _PORT = 28562; //port
public static string connectTo = "example.ddns.net"; //addres
public static IPAddress ipaddress = null;
...
private static void ConnectToServer()
{
int attempts = 0;
bool IsValidIP = IPAddress.TryParse(connectTo, out ipaddress);
if (IsValidIP == false)
{
ipaddress = Dns.GetHostAddresses(connectTo)[0];
Console.WriteLine(Dns.GetHostAddresses(connectTo)[0]);
}
client = new TcpClient();
while (!_clientSocket.Connected)
{
try
{
attempts++;
Console.WriteLine("Connection attempt " + attempts);
_clientSocket.Connect(ipaddress, _PORT);
Thread.Sleep(100);
}
catch (SocketException)
{
Console.Clear();
}
}
Console.Clear();
Console.WriteLine("Connected");
}
What can I change to be able to connect?

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!

Visual Studio Receiving Ethernet UDP (C#)

I'm trying to receive UDP data over ethernet (from a controller) and running into some trouble. I know the controller is sending data because i can see it coming through on wireshark, but all the things I have tried haven't worked. The code below is the closest i've found to being able to receive the data i want.
For more info: The controller IP and port are 192.168.82.27:1743, receiving IP and port on my end are 192.168.82.21:1740
public class UDPListener
{
static UdpClient client = new UdpClient(1740);
public static void Main()
{
try
{
client.BeginReceive(new AsyncCallback(recv), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
while (true)
{
}
}
//CallBack
private static void recv(IAsyncResult res)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 1743);
byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);
//Process code
Console.WriteLine(RemoteIpEndPoint + " : " + Encoding.ASCII.GetString(received));
client.BeginReceive(new AsyncCallback(recv), null);
}
}
This code should work:
public class Receiver
{
private readonly UdpClient udp;
private IPEndPoint ip = new IPEndPoint(IPAddress.Any, 1740);
public Receiver()
{
udp = new UdpClient
{
ExclusiveAddressUse = false
};
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udp.Client.Bind(ip);
}
public void StartListening()
{
udp.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
var bytes = udp.EndReceive(ar, ref ip);
StartListening();
}
}

can not connect to server after some time

Client :
public class TCPClientWrapper : IDisposable
{
private TcpClient tcpClient;
private readonly string address;
private readonly int port;
public TCPClientWrapper(string address, int port)
{
tcpClient = new TcpClient();
this.address = address;
this.port = port;
}
private void TryConnect()
{
tcpClient = new TcpClient();
tcpClient.SendTimeout = 15;
bool isConnected = false;
while (true)
{
try
{
Log.Info("TcpClient, Trying Connect");
tcpClient.Connect(IPAddress.Parse(address), port);
if (SocketConnected(tcpClient.Client))
{
Log.Info("TcpClient, Connected");
isConnected = true;
break;
}
}
catch (Exception e)
{
Log.Info("TcpClient, connection failed. Try to reconnect after 30 seconds, {0}", e.Message);
}
finally
{
if (!isConnected)
Thread.Sleep(30000);
}
}
}
public void SendMessage(string msg)
{
if (!SocketConnected(tcpClient.Client))
{
TryConnect();
}
byte[] buffer = Encoding.UTF8.GetBytes(msg);
tcpClient.Client.Send(buffer);
}
private bool SocketConnected(Socket s)
{
if (!s.Connected)
return false;
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = s.Available == 0;
return !(part1 && part2);
}
public void Dispose()
{
tcpClient.Close();
}
}
Server running as windows service:
public class TcpServer
{
private bool started;
private bool stopped;
private TcpListener tcpListener;
private static ManualResetEvent allDone = new ManualResetEvent(false);
public TcpServer(string url, int port)
{
tcpListener = new TcpListener(IPAddress.Parse(url), port);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Run()
{
if (started) return;
stopped = false;
tcpListener.Start();
Task.Run(() =>
{
Log.Info("Server running");
while (!stopped)
{
allDone.Reset();
tcpListener.BeginAcceptSocket(AcceptCallback, tcpListener);
Log.Info("Accepting socket");
allDone.WaitOne();
}
});
Log.Info("Ping server started");
started = true;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Stop()
{
if (!started) return;
stopped = true;
tcpListener.Stop();
started = false;
Log.Info("Ping server stopped");
}
private void AcceptCallback(IAsyncResult result)
{
try
{
allDone.Set();
if (stopped) return;
Log.Info("Socket accepted");
var listener = (TcpListener)result.AsyncState;
var socket = listener.EndAcceptSocket(result);
Log.Info("Process socket");
ProcessSocket(socket);
}
catch (Exception e)
{
Log.Info("Error accepting callback. {0}", e.Message);
}
}
private void ProcessSocket(Socket socket)
{
try
{
byte[] buffer = new byte[256];
while (!stopped && socket.Receive(buffer) != 0)
{
var msg = Encoding.UTF8.GetString(buffer);
Console.WriteLine(msg);
}
}
catch (Exception e)
{
socket.Close();
Log.Info("Socket closed:{0}", !socket.Connected);
}
}
}
The server is configured in such a way that request to server processed on one IP xxx.xx.xxx.135:5050 and response from server given from xxx.xx.xxx.134:5050
The client works fine for some period of time, but after i get the following error on client side:
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
xxx.xx.xxx.135:5050
What is the reason that the client can't connect to server ?
Check firewall settings on production server
Check whether IP white listing is required
Antivirus might be blocking the request
If no luck, install Advanced REST Client tool on Chrome and manually
test the request
https://forums.asp.net/t/2138734.aspx?A+connection+attempt+failed+because+the+connected+party+did+not+properly+respond+after+a+period+of+time

Android socket connection with a server

I'm trying to connect my Android phone with a Server. On the Server runs a program written in C#. I've tryed to make it with the following code but it doesn't work.
This is the Android code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Socket socket;
int port = 52301;
String ip = "79.16.115.30";
Button b = (Button) findViewById(R.id.myButton);
assert b != null;
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
byte[] b = ip.getBytes();
/*SocketAddress socketAddress = new InetSocketAddress(ip, port);
socket.connect(socketAddress);*/
socket = new Socket(ip, port);
Toast.makeText(v.getContext(), "CONNESSO", Toast.LENGTH_SHORT).show();
} catch (UnknownHostException e) {
Toast.makeText(v.getContext(), "CHI MINCHIA è COSTUI", Toast.LENGTH_SHORT).show();
}catch(IOException e) {
Toast.makeText(v.getContext(), "NO I/O", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
String cause = "Message: " + e.getMessage();
Toast.makeText(v.getContext(), cause, Toast.LENGTH_SHORT).show();
}
}
});
}
I've tryed also to use the code commented but it doesn't work;
This is the program that runs on the Server:
static void Main(string[] args)
{
string ip = Get_external_ip();
int port = 52301;
int max = 10;
IPAddress ipAddress = IPAddress.Parse("192.168.1.56");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); //setto i parametri del socket
Socket sockServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //creo il socket
Socket client;
Console.WriteLine(ip);
try
{
sockServer.Bind(localEndPoint);
sockServer.Listen(max);
while (true)
{
client = sockServer.Accept();
Console.WriteLine(client.RemoteEndPoint.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
private static string Get_external_ip()
{
try
{
WebClient client = new WebClient();
return client.DownloadString("http://icanhazip.com/").TrimEnd('\r', '\n');
}
catch (Exception e)
{
return e.Message;
}
}
First of all, use background Thread for network.
I will give you my working snippet. Try to apply it for your needs.
public class YourClass {
//Server socket variables
private ServerSocket serverSocket;
private DataOutputStream dataOutputStream;
private DataInputStream dataInputStream;
private Socket client;
....
private class SocketServerThread extends Thread {
private int port;
private SocketServerThread(int port) {
this.port = port;
}
#Override
public void run() {
dataInputStream = null;
dataOutputStream = null;
try {
serverSocket = new ServerSocket(port);
isSockedOpened = true;
client = serverSocket.accept(); //wait for client
isClientConnected = true;
Log.d(TAG, "Client connected: " + client.getInetAddress().getHostAddress());
dataInputStream = new DataInputStream(
client.getInputStream());
dataOutputStream = new DataOutputStream(
client.getOutputStream());
String messageFromClient;
while (isClientConnected) {
messageFromClient = dataInputStream.readLine();
handleIncomingMessage(messageFromClient);
}
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage());
}
}
}
To open connection:
public void connect(int port) {
this.port = port;
Thread socketServerThread = new Thread(new SocketServerThread(port));
socketServerThread.start();
}
That's how you check if client connected;
public boolean isConnected() {
return serverSocket.isBound() || client.isConnected();
}
To disconnect:
public void disconnect(boolean needsGathering) {
if (isSockedOpened) {
try {
if (serverSocket != null) {
serverSocket.close();
}
if (dataOutputStream != null) {
dataOutputStream.close();
}
if (dataInputStream != null) {
dataInputStream.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
Log.e(TAG, "Couldn't get I/O for the connection");
Log.e(TAG, e.getMessage());
}
} else {
Log.d(TAG, "Socket was not opened");
}
}
}

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