I have written simple java client/server program and client is trying to sent like below:
os = new DataOutputStream(socket.getOutputStream());
os.writeBytes("HELO\n");
os.writeBytes("MAIL From: person#example.com\n");
os.writeBytes("RCPT To: to#example.com\n");
os.writeBytes("DATA\n");
os.writeBytes("From: person#example.com\n");
os.writeBytes("Subject: testing\n");
os.writeBytes("Hi there\n"); // message body
os.writeBytes("\n.\n");
os.writeBytes("QUIT");
But my server side socket is able to read upto "\n." and then it is waiting to read.
Why is it not reading "QUIT" message after "\n.\n"
Server code:
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readLine();
os.println(line);
}
You need to put a "\n" after QUIT, the stream is reading QUIT, but it doesn't cause the is.readLine() because theres no "new line" character in the string
Related
i'm having trouble with my client/server program in java . I'm able to communicate from my client to my server but when i'm broadcasting from the server to the client it's not working.
There is the part of my program that is not working :
Server :
while (true) {
Socket socket = server.accept();
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome to the server !");
out.flush();
}
Client ( running as a thread):
while(true){
try {
//s is the socket I get from the connection to the server
in = new BufferedReader (new InputStreamReader (s.getInputStream()));
String msg = in.readLine();
System.out.println(msg);
} catch (IOException ex) {
}
}
When I use my client programm I don't receive the message sent by the server . However when i use netcat on my terminal to establish the connection on the server, I got the message . I don't get it. Thanks
The client expects a complete line to be sent:
String msg = in.readLine();
It can only be sure the line is complete if it finds a line terminator character, or if the stream is closed. But the server doesn't send any EOL character, and doesn't close the stream either. So the client keeps waiting for the line to complete.
I am practicing a simple java program where I am demonstrating simple client server interaction. The fist part of message from server gets transferred. Then program just continues to run and does not execute? Do we need to create a new socket for each individual traffic?
Server code
server = new ServerSocket(4587);
System.out.print("Starting the Server on port " + server.getLocalPort() + "\n");
System.out.println("Waiting for client...");
Socket client = server.accept();
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader br1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
br.write("Hello, you are connected to Server. What is your name?");
br.write("\n");
br.flush();
while((s=br1.readLine())!=null)
{
}
br.write("Thank you ");
br.newLine();
br.flush();
}
Client code
String stdin;
System.out.println("Attempting to connect to " + hostname + ":" + port);
client = new Socket("localhost", 4587);
System.out.println("Connection Established");
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((stdin = br.readLine()) != null) {
System.out.println(stdin);
}
BufferedWriter br1 = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
br1.write("Mike");
br1.write("\n");
br1.flush();
while ((stdin = br.readLine()) != null) {
System.out.println(stdin);
}
Server Output
Starting the Server on port4587
Waiting for client....
Client Output
Attempting to connect to :123
Connection Established
Hello you are connected to Server, What is ur name
If this could help..after this both loop
Your server will first create a connection with the client through the accept method. If you wish to have multiple clients you will need to change your code accordingly to accept that.
On the client side, you're using \n to delineate the end of a message. This will work fine. Every time you send a new message use \n to indicate the end of the message.
On the server side, you should continue reading from I/O until you see the \n. At that point you have received the entire message. Process it and than start listening again.
Edit:
Since you are waiting for the name of the client, you could simply do the following on the server:
BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader bin = new BufferedReader(new InputStreamWriter(client.getInputStream()));
// Wait for incoming name from client.
String name = bin.readline();
System.out.println(name);
// Send a reply.
bout.write("Thank you\n");
bout.flush();
Similarly, on the client (assuming bin and bout are defined the same as above):
// Send name to server.
bout.write("Name\n");
bout.flush();
// Get a response from the server and print to console.
String response = bin.readline();
System.out.println(response);
This is because BufferedReader has a default buffer = 8K when in reading process and this process is block I/O, so this will hang in that point. You should read the full message from client by server side.
Your problem is with the loop on the client side. It will be stuck in the loop as it waits to readlines sent from the server infinitely. (ie, after reading the first line from the server, it will expect more lines from the server and wait to read them).
To exit the loop you need to send an EOF signal or end of stream signal (according to the docs: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine%28%29)
inFromClientR.readLine() never stops. any ideas? Am I forgetting something?
Server:
/*{ some code:
send a file with a dataoutputstream to client using a new port(4000) and when transfer is done i want a responce message (e.g. OK) send back to server in the old port(6000)
}*/
ServerSocket listenTransferSocket = new ServerSocket(6000);
Socket connectionTransferSocket = listenTransferSocket.accept();
BufferedReader inFromClientR =
new BufferedReader(new InputStreamReader(connectionTransferSocket.getInputStream()));
System.out.println("Client's response to Transfer: " +inFromClientR.readLine());
Client:
/*{ some code:
receive the file on port (4000) and then the responce is sent to server using the following commands
}*/
Socket fileTransferSocket = new Socket("localhost", 6000);
DataOutputStream outToServerR =
new DataOutputStream(fileTransferSocket.getOutputStream());
outToServerR.writeBytes("Transfer completed " +'\n');
BufferedReader#readLine() tries to fill its buffer with 8192 bytes, regradless of any linefeeds it find meanwhile. Since you have the connection open, the receiving side will wait until 1) you have sent 8192 bytes, or 2) closes the connection.
You would be better off using some other framing mechanism, maybe an ObjectOutputStream/ObjectInputStream.
String line = null;
while ((line = inFromClientR.readLine()) != null) {
// do sth
}
I am creating Client/Server using Java Networking API. My client will send special unicode characters to Server before and after message. Before message it will send \uc001B and after message \uc00C. After message has been send successfully again client will send \r to server. Server can identify by receiving of this that the message sending is done. But my problem here is how can I check in the server whether the message from client has \r.
DataOutputStream outToServer = new DataOutputStream( clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
outToServer.writeBytes("\uc001B");
outToServer.flush();
outToServer.writeBytes(message.toString());
outToServer.writeBytes("\uc001C");
outToServer.flush();
outToServer.writeBytes("\r");
outToServer.flush();
And here is my server Code to read messages from the client
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter( m_clientSocket.getOutputStream()));
String receivingMessage = "";
while (m_bRunThread) {
String clientCommand = in.readLine().toString();
receivingMessage += clientCommand;
System.out.println("Client Says :" + clientCommand);
if (in.equals("\r")) {
System.out.print("Message Receiving from Client Done : "+ m_clientID);
m_bRunThread = false;
}
}
Thanks
You are using readLine(). It removes the newline, whatever it was: it understands all of them. Ergo you cannot possibly tell what the newline character was. Also you cannot possibly care. Every line you read was terminated by a newline character. But you are on fairly dangerous ground using STX and ETX in association with a Reader. You seem to have a protocol definition problem: you are sending STX/ETX and also expecting newlines. Why?
I created an application which establishes connection with the given port and transport data either ways. But I am having issues in reading the data from the server.
try{
Socket skt = new Socket(127.98.68.11, 1111); // connecting to this to get data
String message = "some test message";
if(option.equalsIgnoreCase("send")){
OutputStream outToServer = skt.getOutputStream();
outToServer.write(message); // this is working, message stored on server-side
}else if(option.equalsIgnoreCase("receive")){
BufferedReader in = new BufferedReader (new InputStreamReader(sit.getInputStream()));
String fromServer = in.readLine();
System.Out.Println(fromServer);
}
}catch(IOException io){
io.printStackTrace();
}
In this program everything is working as expected. except in.readline().
I tried running this program in debugging mode, and the by the time compiler reaches this command. is was doing nothing and i can't see the cursor also
It could be because you are trying to do an in.readLine() this requires that the server terminates the "receive" command which it is sending to the client with a newline.. "\n" or "\r\n" along