Hi im writing a code that will connect a windows client to a linux server socket.
I can already established a connection but it seems like the linux server are always cutting my connection after a few seconds without sending me back the response i needed.
Also i already tried using telnet but again after a few seconds the linux server cut my connection.
Is there a problem connecting to a linux server socket using windows socket?
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("IPADDRESS"), 6004);
// 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
{
if (!sender.Connected)
sender.Connect(remoteEP);
string data = new Client().Test();
DE_ISO8583 de = new ISO8583().Parse(data);
data = data.Length.ToString().PadLeft(4, '0') + data;
byte[] msg = Encoding.ASCII.GetBytes(data);
int bytesSent = sender.Send(msg);
//// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Received = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
//sender.Disconnect(true);
//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());
}
The server may be closing the connection due to no activity. Enabling the keepalive option will send an empty datagram to the server periodically to keep the connection alive. See code below
TcpClient client = new TcpClient();
client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
Related
So I have the code listed below for server client communication It works fine as long as you start both programms on the same PC but if I try to connect two seperate Pcs it doesn't work does anyone know where I have to put in the ip? I added some Console.Writelines to getter with there outputs as a comment
// ExecuteClient() Method
static void ExecuteClient(string message)
{
try
{
// Establish the remote endpoint
// for the socket. This example
// uses port 11111 on the local
// computer.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
Console.WriteLine(ipHost); //System.Net.IPHostEntry
IPAddress ipAddr = ipHost.AddressList[0];
Console.WriteLine(ipHost.AddressList.ToString()); //System.Net.IPAddress[]
Console.WriteLine(ipAddr); //gives back an ip v6 address
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
Console.WriteLine(localEndPoint);
// Creation TCP/IP Socket using
// Socket Class Costructor
Console.WriteLine("AddressFamily: " + ipAddr.AddressFamily.ToString()); //InterNetworkV6
Socket sender = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
// Connect Socket to the remote
// endpoint using method Connect()
sender.Connect(localEndPoint);
// We print EndPoint information
// that we are connected
Console.WriteLine("Socket connected to -> {0} ",
sender.RemoteEndPoint.ToString());
// Creation of messagge that
// we will send to Server
byte[] messageSent = Encoding.ASCII.GetBytes("<EOF> " + message);
int byteSent = sender.Send(messageSent);
// Data buffer
byte[] messageReceived = new byte[1024];
// We receive the messagge using
// the method Receive(). This
// method returns number of bytes
// received, that we'll use to
// convert them to string
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}",
Encoding.ASCII.GetString(messageReceived,
0, byteRecv));
// Close Socket using
// the method Close()
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
// Manage of Socket's Exceptions
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());
}
}
//ExecuteServer method
public static void ExecuteServer()
{
// Establish the local endpoint
// for the socket. Dns.GetHostName
// returns the name of the host
// running the application.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
// Using Bind() method we associate a
// network address to the Server Socket
// All client that will connect to this
// Server Socket must know this network
// Address
listener.Bind(localEndPoint);
// Using Listen() method we create
// the Client list that will want
// to connect to Server
listener.Listen(10);
while (true)
{
//Console.WriteLine("Waiting connection ... ");
// Suspend while waiting for
// incoming connection Using
// Accept() method the server
// will accept connection of client
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
while (true)
{
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
Console.WriteLine("Text received -> {0} ", data);
if(data == "<EOF> " + "kill")
{
Application.Exit();
} else if (data == "<EOF> " + "test")
{
Console.Writeline("It works!");
} else
{
byte[] message = Encoding.ASCII.GetBytes("Error 404 message not found!");
// Send a message to Client
// using Send() method
clientSocket.Send(message);
Messagebox1();
}
// Close client Socket using the
// Close() method. After closing,
// we can use the closed Socket
// for a new Client Connection
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
}
}
you can use something like this:
this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.clientSocket.Connect(new IPEndPoint(System.Net.IPAddress.Parse(ip), int.Parse(port)));
and pass the ip address to the "ip" variable.
I have built a server and client which communicate via sockets.
When i run both the server and the client on the same machine both the server and the client receive the messages which are expected.
when i run the server on a VM or a different physical machine and the client on my main machine the server receives messages fine, but the client never receives the reply's
I have made sure to dissable windows firewall and my anti virus on all 3 machines (the 2 physical and one virtual one) to ensure its not a security issue.
The relevant code is as follows
SERVER
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public void StartListening()
{
InstructionProcessor instructionProcessor = new InstructionProcessor();
// 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;
}
}
data = data.Substring(0, data.Length - 5);
// Show the data on the console.
string response = instructionProcessor.doSomething(data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(response);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
}
CLIENT
public static string StartClient(string message, string ip)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
//Declare this at class scope level so it can be returned outside of try/catch blocks
string response = null;
// 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(ip);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
//string hostName = Dns.GetHostName();
//string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString(); ;
//Debug.WriteLine( ipAddress );
// 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 + "<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));
response = 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());
}
return response;
}
}
Maybe because client is receiving more than 1024 byte. Try to increase the size of the received buffer.
Also add if (data.IndexOf("") > -1) into the client project.
I send to the server the text from the console and the server sends it to me.
static void Main(string[] args)
{
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipserv = new IPEndPoint(IPAddress.Parse("46.174.49.48"), 46666);
client.Connect(ipserv);
byte[] data = Encoding.UTF8.GetBytes(Console.ReadLine());
client.Send(data);
client.Receive(data); //here is the error
Console.WriteLine(Encoding.UTF8.GetString(data));
Console.ReadLine();
}
Error: The remote host forcibly broke the existing connection
Server working
You should try a try-catch statement in order to understand better. It is hapenning for one or more of these reasons:
1) You are sending malformed data to the application or (2)The network link between the client and server is going down for some reason...... (3)You have triggered a bug in the third-party application that caused it to crash (4)The third-party application has exhausted system resources It's likely that the first I would say that is the number 1.
Example:::
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());
}
I want a chat application in C# Client and in Java Server
I go through C# Client but I got some Error when I response to Java Server I get the error#
cannot access a disposed object object name='System.Net.Socket.Socket'
class Program
{
static void Main(string[] args)
{
byte[] bytes = new byte[1024];// data buffer for incoming data
// connect to a Remote device
try
{
// Establish the remote end point for the socket
IPHostEntry ipHost = Dns.Resolve("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 95);
Socket Socketsender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint
Socketsender.Connect(ipEndPoint);
Console.WriteLine("\n\n___________________Client Server Chat Application__________________________");
Console.WriteLine("___________________________________________________________________________");
Console.WriteLine("\nSocket Connecting To Java Server...." + Socketsender.RemoteEndPoint.ToString());
// Console.ReadLine();
string data = null;
while (true)
{
//Recieved from Java Server Message
int bytesRec = Socketsender.Receive(bytes);
Console.WriteLine("\nJava Server:: {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Console.ReadLine();
Console.Write("C# Client ::"); // Prompt
string line = Console.ReadLine();
byte[] sendToServer = Encoding.ASCII.GetBytes(line);
// Send the data through the socket
int intByteSend = Socketsender.Send(sendToServer);
// Socketsender.Shutdown(SocketShutdown.Both);
Socketsender.Close();
Console.WriteLine("____________________________________________________________________________");
Console.WriteLine("_________________________End Chat___________________________________________");
// Socketsender.Shutdown(SocketShutdown.Both);
Socketsender.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
You are closing your socket (Socketsender) in he while loop, and then—in the next iteration—calling Receive on it.
Once a socket is closed it is dead,1 and cannot be used for anything. You would need to create a new socket and connect it to the server.
Or better, keep the first socket open.
(You also are performing the close twice, but I'm assuming that is a transcription error.)
1 Insert dead parrot here.
I have written an asynchronous server in C# and a TCP client in Java for and an Android app. The client can send messages fine to the server and they are received when they are sent. However when I send a message from the server to the client, the client only displays the message after the server is shutdown (i.e. when the socket closes).
The strange thing is that I have written a client in C# as well and that receives messages as soon as they are sent.
The C# server and client both use the asynchronous begin* and end* methods and the Java client uses a stream reader/writer.
Can anyone please suggest why the Java client is behaving in this way and how to remedy this?
Thanks.
Client Code:
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
socket = new Socket(serverAddr, SERVERPORT);
try {
if (out != null)
{
//send the message to the server
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
}
//receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
serverMessage = null;
}
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
Server Code:
public void Send(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.
socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), socket);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
//Retrieve the socket from the state object.
Socket clientSocket = (Socket)ar.AsyncState;
//send the data
int bytesSent = clientSocket.EndSend(ar);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
My guess is that the data you send from the server doesn't end with an EOL sequence (\n or \r\n). So the readLine() method at client-side never returns, since it can only return when it's sure the line is terminated (i.e. when an EOL sequence is received, or the connection is closed).