Server Client Communication via Internet (Java) - java

I have written a simple Java TCP Server and a Client (See below).
The idea is quite simple: the Client sends a message to the Server the Server reads it, modify it and sends it back to the client.
import java.io.*;
import java.net.*;
public class ServerTest2 {
public static void main(String[] argv) {
try {
ServerSocket serverSocket = new ServerSocket(2000); // Create Socket and bind to port 2000
System.out.println("Created");
Socket clientSocket = serverSocket.accept(); //Wait for client and if possible accept
System.out.println("Connection accepted");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); // for outputs
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // for inputs
String request; // requst/input of client
String answer; // the answer for the client
System.out.println("Start Waiting");
request = br.readLine(); //Wait for input from client
answer = "answer to "+request;
bw.write(answer); // Send answer to client
System.out.println("send");
bw.newLine();
bw.flush();
//Shut everything down
bw.close();
br.close();
clientSocket.close();
serverSocket.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
The Client Implementation
import java.io.*;
import java.net.*;
public class ClientTest2 {
public static void main(String[] argv) {
try {
String host = "185.75.149.8"; //public ip of router
Socket clientSocket = new Socket(host,2000); //Create and connect Socket to the host on port 2000
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); // for outputs
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // for inputs
String answer;
String request = "HelloWorld";
bw.write(request); //Write to server
bw.newLine();
bw.flush();
System.out.println("Waiting");
answer = br.readLine(); //Wait for answer
System.out.println("Host = "+host);
System.out.println("Echo = "+answer);
//Shut eveything down
bw.close();
br.close();
clientSocket.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
It works perfectly on my local network.
Now I want to use it via the Internet so I installed Port Forwarding on Port 2000 in my Router which sends it to Port 2000 of my PC.
My PC is directly connected to my Router without any Subnets in between.
The Problem is that the Server does not accept the connection(Stops at serverSocket.accept()).
It does not throw an Exception it just waits forever.
The Client does also not throw an Exception (If the Port isn't open it would throw a Connection refused Exception)
This means that the Port Forwarding should work (I have also tested whether the port is open with a Webtool (its open)).
But strangely the Client stops waiting after about 10 seconds and continues with the program.
Since the Port Forwarding should work and my Code works fine in my local Network I absolutely don't know how or where I could find the problem.
I appreciate any help.
Thank you very much!

Related

Server and Client Interactions

Hello programmers on the internet. I am currently stepping through an operating systems book and there are some exercises that involve the following pieces of code.
This is the server code
import java.net.*;
import java.io.*;
public class DateServer{
public static void main(String[] args) {
try {
ServerSocket sock = new ServerSocket(6013);
// now listen for connections
while (true) {
Socket client = sock.accept();
PrintWriter pout = new
PrintWriter(client.getOutputStream(), true);
// write the Date to the socket
pout.println(new java.util.Date().toString());
// close the socket and resume
// listening for connections
client.close();
}
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
This is the client code
import java.net.*;
import java.io.*;
public class DateClient{
public static void main(String[] args) {
try {
//make connection to server socket
Socket sock = new Socket("127.0.0.1",6013);
InputStream in = sock.getInputStream();
BufferedReader bin = new
BufferedReader(new InputStreamReader(in));
// read the date from the socket
String line;
while ( (line = bin.readLine()) != null)
System.out.println(line);
// close the socket connection
sock.close();
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
So to my understanding the server is creating a socket and writing a date value to it. The client is then coming a long and connecting to the server and writing out the value in that socket. Am I interpreting this code correctly? This is my first experience with sockets.
Now for my actual question. I want to have the client connect to the server (and print out a message saying you are connected) and then be able to send a value over to the server so that the server can process it. How would I go about doing this? I have tried tinkering with DataOutputStream and DataInputStream but I have never used either before. Any help would be GREATLY appreciated.
You are correct. You have the server writing to the socket and the client reading from the socket. You want to reverse that.
Server Should look like:
ServerSocket sock = new ServerSocket(6013);
// now listen for connections
while (true)
{
Socket client = sock.accept();
InputStream in = client.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
// read the date from the client socket
String line;
while ((line = bin.readLine()) != null)
System.out.println(line);
// close the socket connection
client.close();
}
The client should look like:
try
{
// make connection to server socket
Socket sock = new Socket("127.0.0.1", 6013);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
// send a date to the server
out.println("1985");
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}

java Socket programming Server Client

I'm trying to program a Server Client program where the CLIENT will be prompt if the SERVER closes or loses connection. What happens is once I connect the server and the client then disconnects the server it doesn't go to the ConnectException part
example: I opened the Server and Client connects, in the Client it will show that "You are connected to the Server", then if the Server disconnects there should be a "Server is disconnected". and when the Server reopens it will prompt the Client that he's connected to the Server
How can I continuously check if the Server is open or disconnected
here's my code:
SERVER
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
System.out.println("Client has connected!");
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
CLIENT
public class Client
{
private static Socket socket;
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
System.out.println("Connected to the Server");
}
catch (ConnectException exception)
{
System.out.println("Server is still offline");
}
catch(IOException ex)
{
System.out.println("Server got disconnected");
}
}
}
Well, the best way to tell if your connection is interrupted is to try to read/write from the socket. If the operation fails, then you have lost your connection sometime.
So, all you need to do is to try reading at some interval, and if the read fails try reconnecting.
The important events for you will be when a read fails - you lost connection, and when a new socket is connected - you regained connection.
That way you can keep track of up time and down time.
you can do like this
try
{
Socket s = new Socket("address",port);
DataOutputStream os = new DataOutputStream(s.getOutputStream());
DataInputStream is = new DataInputStream(s.getInputStream());
while (true)
{
os.writeBytes("GET /index.html HTTP/1.0\n\n");
is.available();
Thread.sleep(1000);
}
}
catch (IOException e)
{
System.out.println("connection probably lost");
e.printStackTrace();
}
or you can simply et connection time out like this socket.setSoTimeout(timeout); to check connectivity
or you can use
socket.getInputStream().read()
makes the thread wait for input as long as the server is connected and therefore makes your program not do anything - except if you get some input and
returns -1 if the client disconnected
or what you can do is structure your code in this way
while(isConnected())
{
// do stuffs here
}

connecting python socket and java socket

I have been trying to send a simple string between a Java client socket and a Python server socket. This is the code for the server socket:
HOST=''
PORT=12000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADRR,1)
s.bind((HOST,PORT))
s.listen(5)
device=variador()
while True:
conn,addr=s.accept()
if data=="turn_on":
respuesta=device.send_order(variador.start_order)
conn.send(respuesta+'\n')
conn.close()
and the client code is:
try {
Socket socket = new Socket("192.168.10.171", 12000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
out.print(command);
out.close();
in.close();
socket.close();
} catch (UnknownHostException e) {
System.err.println("Unknown Host.");
// System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection.");
// System.exit(1);
}
Everything works fine until I try to read the server's response, using this:
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
then the code hangs and the Python server does not receive any information, which I tested using print.
Is there a problem trying to send first and then wait for a response from the server in the Java client?
Any help will be much appreciated.
Well, I discovered that the Java client hangs because the messages sent by the python server were not explicitly finished with \r\n, so the Python code should have been something like this:
HOST = ''
PORT = 12000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADRR, 1)
s.bind((HOST, PORT))
s.listen(5)
device = variador()
while True:
conn, addr = s.accept()
if data == "turn_on\r\n":
respuesta = device.send_order(variador.start_order)
conn.send(respuesta + '\r\n')
conn.close()
I know it should have been quite obvious from the name of the methods in Java, readline() and println, both suggesting that java ends strings with the sequence \r\n
Connect Python And Java Sockets
Install the package jpysocket
pip install jpysocket
https://pypi.org/project/jpysocket
Import Library jpysocket
The Followings Are The Some Example
Python Server :
import jpysocket
import socket
host='localhost' #Host Name
port=12345 #Port Number
s=socket.socket() #Create Socket
s.bind((host,port)) #Bind Port And Host
s.listen(5) #Socket is Listening
print("Socket Is Listening....")
connection,address=s.accept() #Accept the Connection
print("Connected To ",address)
msgsend=jpysocket.jpyencode("Thank You For Connecting.") #Encript The Msg
connection.send(msgsend) #Send Msg
msgrecv=connection.recv(1024) #Recieve msg
msgrecv=jpysocket.jpydecode(msgrecv) #Decript msg
print("From Client: ",msgrecv)
s.close() #Close connection
print("Connection Closed.")
Java Client :
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try{
Socket soc=new Socket("localhost",12345);
DataOutputStream dout=new DataOutputStream(soc.getOutputStream());
DataInputStream in = new DataInputStream(soc.getInputStream());
String msg=(String)in.readUTF();
System.out.println("Server: "+msg);
dout.writeUTF("Ok Boss");
dout.flush();
dout.close();
soc.close();
}
catch(Exception e)
{
e.printStackTrace();
}}}
Python Client :
import jpysocket
import socket
host='localhost' #Host Name
port=12345 #Port Number
s=socket.socket() #Create Socket
s.connect((host,port)) #Connect to socket
print("Socket Is Connected....")
msgrecv=s.recv(1024) #Recieve msg
msgrecv=jpysocket.jpydecode(msgrecv) #Decript msg
print("From Server: ",msgrecv)
msgsend=jpysocket.jpyencode("Ok Boss.") #Encript The Msg
s.send(msgsend) #Send Msg
s.close() #Close connection
print("Connection Closed.")
Java Server :
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try{
ServerSocket serverSocket = new ServerSocket(12345);
Socket soc = serverSocket.accept();
System.out.println("Receive new connection: " + soc.getInetAddress());
DataOutputStream dout=new DataOutputStream(soc.getOutputStream());
DataInputStream in = new DataInputStream(soc.getInputStream());
dout.writeUTF("Thank You For Connecting.");
String msg=(String)in.readUTF();
System.out.println("Client: "+msg);
dout.flush();
dout.close();
soc.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
If you only want to send a single command on the socket connection, then close the OutputStream after writing the command (using Socket.shutdownOutput()). The socket is reading until EOF and you will not receive EOF until you close the socket. hence, your code never proceeds.
Source - java socket InputStream hangs/blocks on both client and server
Hope it helps!

Connection Timed out while connecting two systems on same network via sockets in java

I have a code which has 2 classes, SocketDemo and ServerSocketDemo, when the client (SocketDemo) tried to connect to the server (ServerSocketDemo), it waits for a few seconds and then throws
java.net.ConnectionException : Connection timed out
At that particular time, Server shows that connection is established but the client has now reset the connection and throws Exception
First tell me, is it possible to connect two different systems on same connection via sockets ?
Please consider this code fragment and help !
Client code
import java.net.*;
import java.io.*;
class SocketDemo
{
public static void main(String...arga) throws Exception
{
Socket s = null;
PrintWriter pw = null;
BufferedReader br = null;
System.out.println("Enter a number one digit");
int i=(System.in.read()-48); // will read only one character
System.out.println("Input number is "+i);
try
{
s = new Socket("192.168.1.5",40000);
System.out.println(s);
pw = new PrintWriter(s.getOutputStream());
System.out.println(pw);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(br);
System.out.println("Connection established, streams created");
}
catch(Exception e)
{
System.out.println("Exception in Client "+e);
}
pw.println(i);
pw.flush();
System.out.println("Data sent to server");
String str = br.readLine();
System.out.println("The square of "+i+" is "+str);
}
}
Server Code :
import java.io.*;
import java.net.*;
class ServerSocketDemo
{
public static void main(String...args)
{
ServerSocket ss=null;
PrintWriter pw = null;
BufferedReader br = null;
int i=0;
try
{
ss = new ServerSocket(40000);
}
catch(Exception e)
{
System.out.println("Exception in Server while creating connection"+e);
e.printStackTrace();
}
System.out.print("Server is ready");
while (true)
{
System.out.println (" Waiting for connection....");
Socket s=null;
try
{
System.out.println("connection "+s+ "\n printwriter "+pw+"\n bufferedreader "+br);
s = ss.accept();
System.out.println("Connection established with client");
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("connection "+s+ "\n printwriter "+pw+"\n bufferedreader "+br);
i = new Integer(br.readLine());
System.out.println("i is "+i);
}
catch(Exception e)
{
System.out.println("Exception in Server "+e);
e.printStackTrace();
}
System.out.println("Connection established with "+s);
i*=i;
pw.println(i);
try
{
pw.close();
br.close();
}
catch(Exception e)
{
System.out.println("Exception while closing streams");
}
}
}
}
I am able to use your sample code without problems. It's likely some local firewall rule is preventing your client from completing its connection to the server. Try running your client and server on the same host, using 'localhost' or '127.0.0.1' in the client connection.
See top answer in Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up? for more info.
Also, I note you are not setting socket timeouts for connections or reads in your code. Since you are not setting a timeout in your client socket timeout, the default timeout is zero, which is forever, or more likely whatever your OS default socket timeout is. In general, and especially in production code, not setting a socket timeout for connect or read is a bad idea because it will lead to resource consumption problems that will back up your whole system.
Try setting up your client socket with a connection and read timeout, like this:
//use a SocketAddress so you can set connect timeouts
InetSocketAddress sockAddress = new InetSocketAddress("127.0.0.1",40000);
s = new Socket();
//set connect timeout to one minute
s.connect(sockAddress, 60000);
//set read timeout to one minute
s.setSoTimeout(60000);
System.out.println(s);
pw = new PrintWriter(s.getOutputStream());
...

Java Mulithreaded Server Client

I have a question, I'm currently working on a little project of mine and stumbled upon a dead end. I have a Java Server :
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
ServerSocket welcomeSocket = new ServerSocket(3443);
Socket clientSocket =null;
ClientHandler ch;
while(true)
{
try{
clientSocket = welcomeSocket.accept();
System.out.println("Client connected on port :"+clientSocket.getPort());
ch = new ClientHandler (clientSocket);
Thread t = new Thread(ch);
t.start();
}catch (Exception e){
System.out.println("SERVER CRASH");
}
}
}
}
Then the client connects through the port 3443, a new thread is created with ClientHandler. Now is the problem, in the client side the socket used to connect is still on port 3443, but on the server side the thread is on an arbitrary port, let's say 5433, so the server can communicate with the thread but not the client, because it has no knowledge of what port the thread is using... I'm a bit confused with all this, does the client class is only needed to make the initial connection, then all the communication is done through the ClientHandler class, if so should i also instantiate an object of ClientHandler in the client class?
Here's my client class :
import java.io.*;
import java.net.*;
class TCPClient
{
static Socket clientSocket = null;
public static void main(String argv[]) throws Exception
{
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
BufferedReader ine = null;
DataOutputStream oute = null;
try{
clientSocket = new Socket("localhost", 3443);
oute = new DataOutputStream(clientSocket.getOutputStream());
ine = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host");
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
try{
//send
oute.writeBytes(k.readLine());
//recieve
String line = ine.readLine();
System.out.println("Text received: " + line);
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
}
}
}
The problem is the socket created in client is still connected to Port 3443, and the server is listening to this port, so I won't recieve anything from the server (infinite loop). The clientHandler is on another port. Am i doing it wrong?
You’re calling accept() twice. Call it only once and store the resulting Socket in a variable that you can then hand in to new ClientHandler().
Oh, also, the Socket knows both sides of the communication so it won’t be confused by whatever port the client uses.

Categories