C# Sockets communication between two computers - c#

i want to let 2 c# apps each one is on a separate computer and both connected to the same ADSL router to send messages to each other i know that we have to use Sockets and tried many solutions on the internet but they are all working at the same computer but not working on a separate computers.
i believe that the problem is in the ip addresses but i tried a lot with no good results
is there any simple code to help please
i tried this function on server side
public static void StartServer()
{
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
Console.WriteLine(ipAddress.ToString());
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
try
{
// Create a Socket that will use Tcp protocol
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// A Socket must be associated with an endpoint using the Bind method
listener.Bind(localEndPoint);
// Specify how many requests a Socket can listen before it gives Server busy response.
// We will listen 10 requests at a time
listener.Listen(10);
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
// Incoming data from the client.
string data = null;
byte[] bytes = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Press any key to continue...");
Console.ReadKey();
}
and this function in the client side
public static void StartClient()
{
byte[] bytes = new byte[1024];
try
{
// Connect to a Remote server
// Get Host IP Address that is used to establish a connection
// In this case, we get one IP address of localhost that is IP : 127.0.0.1
// If a host has multiple addresses, you will get a list of addresses
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
// Connect to Remote EndPoint
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

please make sure that your client is connected to the same IP on which server is started. because it seems in your code that your client connecting to host which you getting it from localhost identity. For your testing purpose please hardcode the Server's IP address in your Remoteendpoint. if still the issue same then I will share code to test on a different networks.

Related

No connection could be made because the target machine active refused it?

My problem is weird and i was not able to find a resolution from referring to other threads regarding this. I am getting the error when i run the microsoft Synchronous Server Socket Example, Synchronous Client Socket Example, on two systems which are part of the domain but i do not get this error when i run the same code on two systems which are part of the network but they are not part of the domain! Anyone know what might be causing the issue?
The things i have done to try to resolve are I made sure the port was open, switched off the firewall and antivirus as suggested by others with similar problem.But it has not helped.
Server code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketListener {
// Incoming data from the client.
public static string data = null;
public static void StartListening() {
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and
// listen for incoming connections.
try {
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true) {
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true) {
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data.IndexOf("<EOF>") > -1) {
break;
}
}
// Show the data on the console.
Console.WriteLine( "Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args) {
StartListening();
return 0;
}
}
Client Code::
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient {
public static void StartClient() {
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPAddress ipAddress = IPAddress.Parse("172.21.98.122");//Server IP
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}
public static int Main(String[] args) {
StartClient();
return 0;
}
}

StreamSocketListener only works once; the second call fails

Any help on the issue below would be highly appreciated. I'm using the StreamSocketListener Class to accept TCP/IP connection on my Raspberry Pi 3 running windows IoT 10 Core.
This is my server code so far:
static string _maintenancePort = "8888";
public async static void StartListening()
{
try
{
StreamSocketListener listener = new StreamSocketListener();
var currentSetting = listener.Control.QualityOfService;
listener.Control.QualityOfService = SocketQualityOfService.LowLatency;
listener.ConnectionReceived += SocketListener_ConnectionReceived;
listener.Control.KeepAlive = true;
await listener.BindServiceNameAsync(_maintenancePort);
}
catch (Exception e)
{
Log.WriteErrorLog(e);
}
}
private static async void SocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
try
{
Log.WriteDebugLog("Incoming data...");
Stream inStream = args.Socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(inStream);
string request = await reader.ReadLineAsync();
if (request != null)
{
Log.WriteDebugLog("Received : " + request);
}
}
catch (Exception e)
{
Log.WriteErrorLog(e);
}
}
I wrote the following client code to connect to the socket. This code runs on another machine.
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
private static String response = String.Empty;
public static Socket client;
public static string SendMessageToClient(string ip, int port, string message, bool expectResponse)
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
client = new Socket(ipAddress.AddressFamily,SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
message += "^" + expectResponse.ToString();
// Send test data to the remote device.
Send(client, message);
sendDone.WaitOne();
// Receive the response from the remote device.
if (expectResponse)
{
Receive(client);
receiveDone.WaitOne();
}
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
return response;
}
catch (Exception e)
{
Log.Write(e, false);
return "";
}
}
private static void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Log.WriteSingleMessage(String.Format("Sent {0} bytes to server.", bytesSent), false);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Log.Write(e, false);
}
}
}
The client code is triggered by a button click event. The problem that I'm facing is that the server code above only works once. If I send a message to the server with the client code, the server processes the string perfect. However, if I hit the button a second time, the SocketListener_ConnectionReceived event is triggered but no data is coming in. I've tried several classes for ConnectionReceived but they all behave the same.
I checked with netstat on the Raspberry Pi if the server is listening and it is.
TCP 0.0.0.0:8888 0.0.0.0:0 LISTENING
Even child processes are created for handling the connection as you would expect from an Async calls. The client code closes the socket after it received a message that the data has been send (waitOne()) and the socket on the client machines changes to CLOSE_WAIT.
TCP 10.0.102.10:8888 10.0.100.11:31298 CLOSE_WAIT
TCP 10.0.102.10:8888 10.0.100.11:31299 ESTABLISHED
Can anyone help me out and point me in the right direction as to what I'm doing wrong. any help would be highly appreciated.
You can try to use synchronous methods instead asynchronous methods for socket client. It will work. Please refer to following code:
public void SendMessageToClientSync(string ip, int port, string message, bool expectResponse)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(message);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
if(expectResponse)
{
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
}
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

Receiving SocketException (0x80004005) when logging into VPN

I have been troubleshooting an issue that I encountered when using a library called AMQP .Net Lite (https://github.com/Azure/amqpnetlite) and have determined that it can be reproduced using a simple .NET Sockets client and server. My repro environment uses a client that sends simple text messages to the server based on some Microsoft samples (see below).
I have noticed after I sign into my company VPN that messages fail to transfer with the following error:
SocketException : System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
I am running both client and server locally on my machine when I encounter the issue.
I have read about this exception and learned that one cause is that the network link has gone down for some reason. This makes sense as logging into VPN must temporarily break the connection, thereby causing the exception. However, one interesting observation is that this problem only occurs when the server is hosting using IPv6. If I force it to use IPv4, then there is no loss of connectivity. Is there a simple explanation for that?
I am also wondering if there is some way to detect that the Socket is in a bad state without sending data? Are there some properties on the Socket I can inspect such that I can detect an issue and force a reconnect? If not, what do people typically do in this situation to ensure the failed messages are accounted for after reconnection?
Interestingly, with my test client, I have to send 2 messages before the exception is thrown, but neither message is received by the server (see picture below).
I am not a networking expert so bear with me if this is fundamental stuff.
Here is my client:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class SynchronousSocketClient
{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Environment.MachineName);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetworkV6,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
Console.WriteLine("Press any key to send a message...");
int i = 0;
while (true)
{
Console.ReadLine();
// Send the data through the socket.
int bytesSent = sender.Send(msg);
Console.WriteLine(++i + " messages sent");
}
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
public static int Main(String[] args)
{
StartClient();
return 0;
}
}
Here is my server:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.IPv6Any, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetworkV6,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data = Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine(data);
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
Here is a screenshot of the problem:

send socket request from .net web service (asmx)

I went to request to open socket from web service to be like notification when the database change . The client is request to web service when it's connection to internet to apply to web service to get his IP Address then web service can send in this IP socket when database change . And client have socket open response the request .
Code of web service in Remote host
[WebMethod]
public string GetMyIpAddress()
{
string adree = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; //get client request ip address
byte[] bytes = new byte[1024];
try
{
IPAddress ipaddress = IPAddress.Parse(adree);
IPEndPoint remote = new IPEndPoint(ipaddress, 1093);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remote);
byte[] meg = Encoding.ASCII.GetBytes("This is a test<EOF>"); // send message to client in it's ip address
int bytesend = sender.Send(meg);
int byterecive = sender.Receive(bytes);
string red = Encoding.ASCII.GetString(bytes, 0, byterecive);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
return(red);
}
catch (Exception e)
{
return(e.ToString());
}
}
Code of client socket
class Program
{
public static string data = null;
static void Main(string[] args)
{
byte[] bytes = new byte[1024];
IPHostEntry iphostinfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipaddress = iphostinfo.AddressList[0];
IPEndPoint localendpoint = new IPEndPoint(ipaddress, 1093);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localendpoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket hander = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytsize = hander.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytsize);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] meg = Encoding.ASCII.GetBytes(data);
hander.Send(meg);
hander.Shutdown(SocketShutdown.Both);
hander.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
}
The problem when i request to web service to get my client IP address and send to this IP address for test i get this problem :
System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or est ablished connection failed because connected host has failed to respond 41.218.1
9.226:1093
Please help me how can solve this problem ?

Send and Receive Data to iSeries Socket (AS400) C#

I'm trying to develop a class that connect to iSeries (as400 - PGM Program) by sockets. The connection works fine but when I try to send data and receive it's get an error.
This is the code:
class Program
{
public static void StartClient()
{
byte[] bytes = new byte[1024];
string desaip = "10.112.2.11";
// Connect to a remote device.
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses(desaip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress[0], 42125);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
#region forma A
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("PRUEBAIB");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
sender.ReceiveTimeout = 10000;
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
#endregion forma A
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
What could be wrong?
Check the software that is supposed to be listening to that port on the iSeries. Make sure that it is running, that it is listening to that port. Work with that job, and look at the job log to see what messages were sent. Check the program stack to see what statement it is on, which may help determine what has happened. The open files & I/O stats might also help.

Categories