This question already has answers here:
Importance of the new line "\n" in Java networking
(2 answers)
Closed 4 years ago.
I have a Client and a Server, they should have a communication in both ways. Everything worked well, client sent some information to server, and server did something with that information. Now that I tried to implement server replying to. After I've tried implementing that, both programs are now stuck in an infinite loop, waiting for information from the other side.
Here is my code for the server side:
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
logger.log(Level.INFO, "args[0]: {0} args[1]: {1} args[2]: {2} args[3] {3}", new Object[]{args[0], args[1], args[2], args[3]});
pathToExcel = args[0];
pathToDatabase = args[1];
numberOfAccounts = Integer.parseInt(args[2]);
portNumber = Integer.parseInt(args[3]);
listIE = new ArrayList<>();
listIE = Loader.getList(numberOfAccounts, pathToExcel);
DBBroker.createTables(pathToDatabase);
System.out.println("Check value: " + DBBroker.checkDB());
if (DBBroker.checkDB() == false) {
DBBroker.insertData();
DBBroker.insertDataBalance();
} else {
System.out.println("Data has already been inserted into the database");
}
startServer();
}
public static void startServer() throws IOException {
//ServerSocket ss = new ServerSocket(portNumber);
ServerSocket ss = new ServerSocket(portNumber);
logger.log(Level.INFO, "Server started on port number: {0}", portNumber);
try {
while (true) {
Socket clientSocket = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream clientOutput = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Client connected ");
//***************************************************************************
String answer = input.readLine();
//***************************************************************************
System.out.println("prosao readline");
//logger.info("Client logged in on port " +portNumber);
String[] niz = answer.split("_");
//System.out.println("niz: " +Arrays.toString(niz));
serverPortNumber = Integer.parseInt(niz[0]);
accountName = niz[1];
receiverName = niz[2];
amount = Integer.parseInt(niz[3]);
//System.out.println("Server port number: " +serverPortNumber + " accountname: " +accountName +" receiver name: " +receiverName + " amount: " +amount);
parseRequestFromClient();
System.out.println("Prosao request");
clientOutput.writeBytes("Kraj");
clientSocket.close();
}
//ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And here is my code for the client side:
public static void main(String[] args) throws IOException {
String messageFromServer = "";
logger.log(Level.INFO, "args[0]: {0} args[1]: {1} args[2]: {2} args[3] {3}", new Object[]{args[0], args[1], args[2], args[3]});
Socket socket = new Socket("localhost", Integer.parseInt(args[0]));
//logger.info("args[0]: " +args[0] +" args[1]: " +args[1] +" args[2]: " +args[2] +" args[3] " +args[3]);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String dataForServer = args[0]+"_"+args[1]+"_"+args[2]+"_"+args[3];
System.out.println("Data for server: " +dataForServer);
outputStream.writeBytes(dataForServer);
System.out.println("prosao dataforserver");
//***************************************************************************
String answer = input.readLine();
//***************************************************************************
System.out.println("prosao readline");
System.out.println(answer);
socket.close();
}
Server side gets stuck at the ss.accept() line, while the Client side gets stuck at input.readLine()
I didn't add the whole project because a large portion of it is not relevant to the problem and it has a lot of code.
Your server was blocking on readLine(). It blocks for a line terminator. The client was only sending a raw string. The solution is to send a line terminator with each raw string.
The same applies when the server responds to the client.
As Simon has pointed out a printwriter would be a good choice if your message protocol is to pass line terminated strings.
Related
I'm trying to answer the clients message with an echo, but I am not figuring how to. My client sends a message, but then I reverse the papers and the program doesn't proceed (gets stuck in line
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
of the server). I guess it is about closing the inputstream, but when I do that, that closes the socket and I have no way to reuse it. I have managed do do this with readUTF and with socket.shutDownInput, but I want a easiest way - like close or flush, which I am not getting.
Client
public class SocketClient {
public static void main( String[] args ) throws IOException {
// Check arguments
if (args.length < 3) {
System.err.println("Argument(s) missing!");
System.err.printf("Usage: java %s host port file%n", SocketClient.class.getName());
return;
}
String host = args[0];
// Convert port from String to int
int port = Integer.parseInt(args[1]);
// Concatenate arguments using a string builder
StringBuilder sb = new StringBuilder();
for (int i = 2; i < args.length; i++) {
sb.append(args[i]);
if (i < args.length-1) {
sb.append(" ");
}
}
String text = sb.toString();
// Create client socket
Socket socket = new Socket(host, port);
System.out.printf("Connected to server %s on port %d %n", host, port);
// Create stream to send data to server
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// Send text to server as bytes
out.writeBytes(text);
out.writeBytes("\n"); // devia meter readline a null...
System.out.println("Sent text: " + text);
System.out.println(socket.getInetAddress().getHostAddress() + " " + socket.getPort());
//out.close();
//socket.shutdownOutput(); trials...
////////////////////////////////////////////
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("here");
// Receive data until client closes the connection
String response;
while ((response = in.readLine()) != null)
System.out.printf("Received message with content: '%s'%n", response); // here is where client doesn't proceed - he doesn't get the echo
Server
public class SocketServer {
public static void main( String[] args ) throws IOException {
// Check arguments
if (args.length < 1) {
System.err.println("Argument(s) missing!");
System.err.printf("Usage: java %s port%n", SocketServer.class.getName());
return;
}
// Convert port from String to int
int port = Integer.parseInt(args[0]);
// Create server socket
ServerSocket serverSocket = new ServerSocket(port);
System.out.printf("Server accepting connections on port %d %n", port);
// wait for and then accept client connection
// a socket is created to handle the created connection
Socket clientSocket = serverSocket.accept();
System.out.printf("Connected to client %s on port %d %n",
clientSocket.getInetAddress().getHostAddress(), clientSocket.getPort());
// Create stream to receive data from client
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Receive data until client closes the connection
String response;
while ((response = in.readLine()) != null)
System.out.printf("Received message with content: '%s'%n", response);
/////////////////////////////////////////////
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); // he doesn't reach here
System.out.println("here-serv");
System.out.println(clientSocket.getInetAddress().getHostAddress() + " " + clientSocket.getPort());
// Send text to server as bytes
out.writeBytes("echo");
I actually believe this problem has something with the readline from server, it is not getting a null - but the client sends a "\n"! Can you find my code mistake? Thanks
I have been tasked with getting a simple TCP Client to timeout. The client works as expected, however I cannot seem to get the client to timeout when the client does not receive an input for 3 seconds or more.
I have a basic understanding of SO_TIMEOUT, but can't get it to work here.
Please help
Here is my code:
TCPClient
private static final String host = "localhost";
private static final int serverPort = 22003;
public static void main(String[] args) throws Exception
{
try
{
System.out.println("You are connected to the TCPCLient;" + "\n" + "Please enter a message:");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
#SuppressWarnings("resource")
Socket client = new Socket(host, serverPort);
client.setSoTimeout(3000);
while(true)
{
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
String input = inFromUser.readLine();
outToServer.writeBytes(input + "\n");
String modedInput = inFromServer.readLine();
System.out.println("You Sent: " + modedInput);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
System.out.println("Slept-in");
e.getStackTrace();
}
}
}
catch(SocketTimeoutException e)
{
System.out.println("Timed Out Waiting for a Response from the Server");
}
}
setSoTimeout doesn't do what you think it does. From the Javadoc:
With this option set to a non-zero timeout, a read() call on the
InputStream associated with this Socket will block for only this
amount of time.
It's a timeout for reads from the socket, so reads() will return after 3 seconds even if there's no data. It's not a timeout for socket inactivity - i.e. the socket won't disconnect after being idle for 3 seconds.
The code below is part of a larger attempt; it tries to transfer a file's details between server and client and fails miserably. Server writes 3 elements to socket, client should receive same 3 elements. Client blocks after reading first element. What am I doing wrong?!?
public class SocketIssues {
static void client() throws Exception {
new Thread() {
#Override
public void run() {
try {
Thread.sleep(1000); // enough time for server to open its socket
Socket s = new Socket("localhost", 50001);
final DataInputStream dis = new DataInputStream(s.getInputStream());
final BufferedReader in = new BufferedReader(new InputStreamReader(dis));
System.out.println("CLIENT STARTED");
System.out.println("Operation: " + in.readLine());
System.out.println("Length: " + dis.readLong());
System.out.println("Name: " + dis.readUTF());
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
static void server() throws Exception {
ServerSocket ss = new ServerSocket(50001);
Socket s = ss.accept();
System.out.println("SERVER: client connected");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(dos));
long l = 2194;
String nume = "The file name";
out.write("FILE1" + System.lineSeparator());
out.flush();
dos.writeLong(l);
dos.flush();
dos.writeUTF(nume);
dos.flush();
System.out.println("SERVER: done sending" + System.lineSeparator());
}
public static void main(String[] args) throws Exception {
client();
server();
}
}
Try sticking with just the DataOutputStream instead of mixing them up between data and a buffered writer and use the read/write UTF() method like you're already doing with the last object:
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
long l = 2194;
String nume = "The file name";
dos.writeUTF("FILE1");
dos.flush();
dos.writeLong(l);
dos.flush();
dos.writeUTF(nume);
dos.flush();
System.out.println("SERVER: fisier trimis" + System.lineSeparator());
then in the client:
final DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("CLIENT STARTED");
System.out.println("Operation: " + dis.readUTF());
System.out.println("Length: " + dis.readLong());
System.out.println("Name: " + dis.readUTF());
Essentially, there's 2 layers of buffering going on. It's possible that when you call readLine() from the BufferedReader, it goes ahead and steals more bytes from the underlying stream because, well, that's what it's supposed to do. Then, when you go back to the DataInputStream and try to read an object, the preamble is gone (BufferedReader stole it), and it'll block waiting for it, eventhough there's bytes in the stream.
m new in socket programming...i hv to create a server that stores name & id from a client in a queue and then it stores all the inputs given by the client in another queue. when the client writes 'test', server retrieves all the stored data as the client types some value i.e. integer...when client types 'resume' server again starts storing client's given input in the queue...if client types 'exit' server sends back the client's name and id and starts waiting for a ne client. And the receives those info and closes the socket.
Problem faced:
m facing problem in retrieving the data from queues. when i type exit, i can see the name and id which i'm retriving through the for loop. if i put this line outToClient.writeBytes("Thank You!"+'\n'); after the for loop then it shows the client's name & id but the client doest go off.
in the if else condition while checking for 'test' again i'm facing problem in retrieving data. server asks for integer..client types an integer and then i dont get the data from server.
here is my code
Server Side:
import java.io.*;
import java.net.*;
import java.util.*;
class server
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String replySentence;
ServerSocket welcomeSocket= new ServerSocket(6789);
while(true)
{
System.out.println("#########Server Waiting#########");
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
Queue<String> qe = new LinkedList<String>();
outToClient.writeBytes("Enter your Name and ID Please..."+'\n');
for(int i=0;i<=1;i++)
{
clientSentence = inFromClient.readLine();
qe.add(clientSentence);
}
outToClient.writeBytes("Thank you! You may now proceed further..."+'\n');
Queue<String> chatq = new LinkedList<String>();
clientSentence = inFromClient.readLine();
while(!clientSentence.equals("exit"))
{
if(clientSentence.equals("test"))
{
outToClient.writeBytes("Enter Integers to fetch data or 'resume' to continue..."+'\n');
clientSentence = inFromClient.readLine();
while(!clientSentence.equals("resume"))
{
replySentence = chatq.remove();
outToClient.writeBytes(replySentence+'\n');
clientSentence = inFromClient.readLine();
}
if(clientSentence.equals("resume"))
{
outToClient.writeBytes("You may now proceed again..."+'\n');
clientSentence = inFromClient.readLine();
}
}
else
{
chatq.add(clientSentence);
clientSentence = inFromClient.readLine();
}
}
if(clientSentence.equals("exit"))
{
outToClient.writeBytes("Client Name & ID: "+'\n');
for(int i=0;i<=1;i++)
{
replySentence = qe.remove();
outToClient.writeBytes(replySentence+'\n');
}
}
}
}
}
Client Side:
import java.io.*;
import java.net.*;
import java.util.*;
class client
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
InetAddress inetAddress=InetAddress.getLocalHost();
System.out.println(inetAddress);
Socket clientSocket = new Socket(inetAddress,6789);
while(true)
{
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence+'\n');
for(int i=0;i<=1;i++)
{
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence+'\n');
}
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
sentence = inFromUser.readLine();
while(!sentence.equals("exit"))
{
if(sentence.equals("test"))
{
outToServer.writeBytes(sentence+'\n');
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
sentence = inFromUser.readLine();
while(!sentence.equals("resume"))
{
outToServer.writeBytes(sentence+'\n');
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
sentence = inFromUser.readLine();
}
if(sentence.equals("resume"))
{
outToServer.writeBytes(sentence+'\n');
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
sentence = inFromUser.readLine();
}
}
else
{
outToServer.writeBytes(sentence+'\n');
sentence = inFromUser.readLine();
}
}
if(sentence.equals("exit"))
{
outToServer.writeBytes(sentence+'\n');
modifiedSentence=inFromServer.readLine();
System.out.println("From Server: "+modifiedSentence + '\n');
for(int i=0;i<=1;i++)
{
modifiedSentence=inFromServer.readLine();
System.out.println(modifiedSentence + '\n');
}
clientSocket.close();
break;
}
}
}
}
I assume this is [homework] however...
You are mixing binary (DataOutputStream) with text (BufferedReader). You should use one or the other or you are bound to confuse yourself.
It appears you want to send text so I would use BufferedReader and PrintWriter. DataOutputStream is better suited for binary protocols.
My aim is to send a message from python socket to java socket. I did look out on the resource mentioned above. However I am struggling to make the Python client talk to Java server. Mostly because (End of line) in python is different from that in java.
say i write from python client: message 1: abcd message 2: efgh message 3: q (to quit)
At java server: i receive message 1:abcdefghq followed by exception because the python client had closed the socket from its end.
Could anybody please suggest a solution for a consistent talk between java and python.
Reference I used: http://www.prasannatech.net/2008/07/socket-programming-tutorial.html
Update: I forgot to add, I am working on TCP.
My JAVA code goes like this:(server socket)
String fromclient;
ServerSocket Server = new ServerSocket (5000);
System.out.println ("TCPServer Waiting for client on port 5000");
while(true)
{
Socket connected = Server.accept();
System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
while ( true )
{
fromclient = inFromClient.readLine();
if ( fromclient.equals("q") || fromclient.equals("Q") )
{
connected.close();
break;
}
else
{
System.out.println( "RECIEVED:" + fromclient );
}
}
}
My PYTHON code : (Client Socket)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))
while 1:
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
if (data <> 'Q' and data <> 'q'):
client_socket.send(data)
else:
client_socket.send(data)
client_socket.close()
break;
OUTPUT::
ON PYTHON CONSOLE(Client):
SEND( TYPE q or Q to Quit):abcd ( pressing ENTER)
SEND( TYPE q or Q to Quit):efgh ( pressing ENTER)
SEND( TYPE q or Q to Quit):q ( pressing ENTER)
ON JAVA CONSOLE(Server):
TCPServer Waiting for client on port 5000
THE CLIENT /127.0.0.1:1335 IS CONNECTED
RECIEVED:abcdefghq
Append \n to the end of data:
client_socket.send(data + '\n')
ya..you need to add '\n' at the end of the string in python client.....
here's an example...
PythonTCPCLient.py
`
#!/usr/bin/env python
import socket
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.sendall("Hello\n")
data = sock.recv(1024)
print "1)", data
if ( data == "olleH\n" ):
sock.sendall("Bye\n")
data = sock.recv(1024)
print "2)", data
if (data == "eyB}\n"):
sock.close()
print "Socket closed"
`
Now Here's the java Code:
JavaServer.java
`
import java.io.*;
import java.net.*;
class JavaServer {
public static void main(String args[]) throws Exception {
String fromClient;
String toClient;
ServerSocket server = new ServerSocket(8080);
System.out.println("wait for connection on port 8080");
boolean run = true;
while(run) {
Socket client = server.accept();
System.out.println("got connection on port 8080");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
fromClient = in.readLine();
System.out.println("received: " + fromClient);
if(fromClient.equals("Hello")) {
toClient = "olleH";
System.out.println("send olleH");
out.println(toClient);
fromClient = in.readLine();
System.out.println("received: " + fromClient);
if(fromClient.equals("Bye")) {
toClient = "eyB";
System.out.println("send eyB");
out.println(toClient);
client.close();
run = false;
System.out.println("socket closed");
}
}
}
System.exit(0);
}
}
`
Reference:Python TCP Client & Java TCP Server
here is a working code for the same:
Jserver.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Jserver{
public static void main(String args[]) throws IOException{
ServerSocket s=new ServerSocket(5000);
try{
Socket ss=s.accept();
PrintWriter pw = new PrintWriter(ss.getOutputStream(),true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br1 = new BufferedReader(new InputStreamReader(ss.getInputStream()));
//String str[20];
//String msg[20];
System.out.println("Client connected..");
while(true)
{
System.out.println("Enter command:");
pw.println(br.readLine());
//System.out.println(br1.readLine());
}
}
finally{}
}
}
Client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 5000 # Reserve a port for your service.
s.connect((host, port))
while 1:
print s.recv(5000)
s.send("message processed.."+'\n')
s.close
I know it is late but specifically for your case I would recommend RabbitMQ RPC calls. They have a lot of examples on their web in Python, Java and other languages:
https://www.rabbitmq.com/tutorials/tutorial-six-java.html
for the people who are struggling with,
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
your can also use
.encode() to send the data