This question already has answers here:
Java Socket why server can not reply client
(4 answers)
Closed 3 years ago.
I'm very new to socket programming. I have a requirement on continuously sending and receiving data between client and server. Below the process flow needs to be done.
Client sends "Client Hello" message to Server.
Server sends "Server hello" message to Client.
Client Sends "What is your server id?" message to Server
Server sends "My ID is #1" message to Client.
Client sends "Thank you" message to Server.
Server send "You are welcome" message to client
I tried to do this using Java sockets API. But i can't send multiple messages using a one socket. only 1 and 2 messages were able to transmit. Can someone tell me a way to achieve this requirement? Highly appreciate if someone give me an advise on this.
This is the server side program
package socketserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer{
public static void main(String args[]){
final int SocketServerPORT = 4000;
try{
ServerSocket serverSocket = new ServerSocket(SocketServerPORT);
System.out.println("Server is started with port"+ serverSocket.getLocalPort());
System.out.println("Waiting for connection...");
Socket socket = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Receiving Client Hello
System.out.println(input.readLine());
PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
//Sending Server Hello
output.write("Server Hello");
output.flush();
//Recieving Client message asking regarding Server ID
System.out.println(input.readLine());
//Sending Server ID to client
output.write("MY Server ID is #1");
output.flush();
//Recieving Client Thank you message
System.out.println(input.readLine());
//Sending Welcome message to Client
output.write("You are welcome.");
output.flush();
output.close();
input.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below is the Client Side program
package socketclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient {
public static void main(String[] args) {
final int socketServerPORT = 4000;
final String host="127.0.0.1";
try {
Socket clientSocket=new Socket(host,socketServerPORT);
PrintWriter output = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
//Sending Client Hello
output.println("Client Hello");
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Receiving Server Hello
System.out.println(input.readLine());
//Asking for Server ID
output.println("What is your Server ID");
output.flush();
//Receving Server ID
System.out.println(input.readLine());
//Sending Thank you message to Server
output.println("Thank you.");
output.flush();
//Receving Welcome message from Server
System.out.println(input.readLine());
output.close();
input.close();
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You are reading lines but you aren't writing lines. The readLine() method blocks until a line terminator or end of stream occurs. You need to either append \n to each message or use println() instead of write().
Related
This is the code for my server, its supposed to take an input from the user, print it into console, then send it back to the user.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class DateServer {
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(10219);
Socket s = listener.accept();
InputStreamReader in = new InputStreamReader(s.getInputStream());
BufferedReader input = new BufferedReader(in);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println("connected");
out.flush();
System.out.println("connected");
String test;
while (true) {
try {
test = input.readLine();
System.out.println(test);
out.println(test + " is what I recieved");
out.flush();
} catch(Exception X) {System.out.println(X);}
}
}
}
This is the code for the client:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;
public class DateClient {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws Exception {
System.out.println("Enter IP Address of a machine that is");
System.out.println("running the date service on port 10219:");
String serverAddress = keyboard.next();
Socket s = new Socket(serverAddress, 10219);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
System.out.println(input.readLine());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
} catch(Exception X){System.out.println(X);}
}
}
}
This was designed to work across a LAN network. I have no idea why it doesn't work, all that happens is the client will get the message "connected" and nothing else will happen, no matter what is typed into the client end. I'm a noob when it comes to java, but after a bunch of googling and searching through the java libraries, I can't seem to make it work. What did I do wrong?
You send one line from the server to the client, but in your client you wait for two lines before accepting user input to be sent to the server.
Bearing in mind that input.readLine() will block until data is received, can you spot the deadlock here:
Server:
out.println("connected");
while (true) {
try {
input.readLine();
}
}
Client:
input.readLine();
while(true) {
try {
input.readLine();
out.println(keyboard.next());
}
}
(extraneous code trimmed away to show just the problematic sequence of statements)
Both your client and server mutually wait for each other trying to do input.readLine().
This can be easily seen if you remove server's out.println("connected") and its corresponding client's first input.readLine().
On the client, you should probably write first and only then read the response. Try reordering the following lines:
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
to get
out.println(keyboard.next());
out.flush();
System.out.println(input.readLine());
In the client, try changing
PrintWriter out = new PrintWriter(s.getOutputStream());
System.out.println(input.readLine());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
} catch(Exception X){System.out.println(X);}
}
to
PrintWriter out = new PrintWriter(s.getOutputStream());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.nextLine());
out.flush();
} catch(Exception X){System.out.println(X);}
}
Your client is trying to read two lines, but your server sends just one, then polls for input, so both are locked. Also, sinc your server is reading line-by-line, your client should be sending data line-by-line.
I created a java application in Eclipse to connect Plant Simulation via Socket. My first step is just sending and receiving messages "Hello" between plant simulation (PS) and my java application. It worked, but I thought it was strange.
Java application is server. PS is client.
I run "ServerJava" first time. When I active "MyClientSocket" in PS, message "Hallo Plant Simulation" is received in PS. Then I run method "m_sendMessage" in PS to send message "Hallo Java" to ServerJava. It is sent to ServerJava, but its not printed in console. If I deactive "MyClientSocket" to disconnect, its printed in console.
How can message be printed immediately, when I run the method "m_sendMessage" in PS?
My codes:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerJava {
public static void main(String[] args) {
ServerSocket listener = null;
String line = null;
Socket clientSocket = null;
// ServerSocket with Port 30005
try {
listener = new ServerSocket(30005);
} catch (IOException e) {
System.out.println(e);
System.exit(1);
}
try {
System.out.println("Server is waiting to accept user...");
clientSocket = listener.accept();
System.out.println("Accept a client!");
BufferedReader is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter os = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
while (true) {
// Message to client: Hello Plant Simulation
os.write("Hello Plant Simulation");
os.flush();
//Message from client: Hello Java
line = is.readLine();
System.out.println(line);
os.close();
}
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
System.out.println("Sever stopped!");
}
}
Code for m_sendMessage
Thank you in Advance for your help.
I have written two-way client-server communication in which client first sends the message and then server sends the reply. However, client is blocked while reading the reply sent by server( i.e Nothing is printed at client side however, server has sent the reply correctly). Below is the code :-
Server code:-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
// Socket for accepting connections.
private static Socket socket;
public static void main( String[] args )
{
try
{
int port = 2550;
// Creating server socket on specified port.
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started listening on port "+port);
while(true)
{
// Accept the connection and read the message.
socket = serverSocket.accept();
BufferedReader br = new BufferedReader( new InputStreamReader( socket.getInputStream()));
String message = br.readLine();
System.out.println("Message recieved from client is :- " + message);
// Prepare and send the response back to client.
BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream()));
String reply = "Thanks.Your reply has been recieved";
bw.write(reply);
bw.flush();
}
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch( Exception e )
{
}
}
}
}
Client code :-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client
{
private static Socket socket;
public static void main( String[] args )
{
try
{
String host = "localhost";
int port = 2550;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
// Send the message to the server.
BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream()));
String message = "This is the message from Client.\n";
bw.write(message);
bw.flush();
System.out.println("Message sent to the server :- " + message);
// Get the reply from the server.
BufferedReader br = new BufferedReader( new InputStreamReader( socket.getInputStream()));
String reply = br.readLine();
System.out.println("Message recieved from the server :- " + reply);
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
// Closing the socket.
try
{
socket.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
}
}
D:\Java_P>java Server
Server started listening on port 2550
Message recieved from client is :- This is the message from Client.
D:\Java_P>java Client
Message sent to the server :- This is the message from Client.
I
This is happening because your server sends "Thanks. Your reply has been recieved" which does not contain any newline character. Reason is because in the client, buffered reader readline method blocks till it finds a newline character.
Make following changes:
String reply = "Thanks.Your reply has been recieved\nDummy line 1";
Now you can see the lines in your client logs.
I recently programmed a simple Java server, and a client to test the server. The server is supposed to receive messages from the client, and send a random substring of the message back. The problem is this: When I send the message using the client program, the server does not respond. Then, when I kill the client program, the server leaps into action, and attempts to send the data back to the client. The server reads the data correctly but starts processing it only when I stop the client program.
This is the client code:
import java.io.*;
import java.net.*;
class ServerTest{
public static void main(String args[]) throws Exception{
Socket clientSocket = new Socket(myIpAdress, 8001);
//Send the message to the server
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String sendMessage = "randSubstring:StackOverflowIsAwsome";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent: "+sendMessage);
String message = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())).readLine();
System.out.println("Message received from the server : " +message);
clientSocket.close();
}
}
My server code consists of two classes. This one is the listener:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerListener {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket socket = new ServerSocket(8001);
while(true) {
Socket connectionSocket = socket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
//DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = input.readLine();
if(clientSentence.startsWith("randSubstring:")){
Thread connection = new Thread(new ServerConnection(connectionSocket, clientSentence));
connection.start();
}
Thread.sleep(300);
}
}
}
This is the thread that will not start until the client is stopped:
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Random;
public class ServerConnection implements Runnable{
private Socket serverConnection;
private String sentence;
public ServerConnection(Socket connection, String clientSentence){
serverConnection = connection;
sentence = clientSentence;
}
#Override
public void run() {
Random r = new Random();
String substring = sentence.substring(0, r.nextInt(sentence.length()));
try {
OutputStream os = serverConnection.getOutputStream();
OutputStream out = new BufferedOutputStream(os);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write(substring);
bw.close();
out.close();
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am using a Macintosh with Yosemite. Is this happening because I am trying to run the programs on the same computer, or would the problem occur if the programs were run from different computers? Any help is appreciated.
In the server you do a readLine(..), which means that it will wait for a end-of-line character.
But in your sender code, you just send a string with no line ending.
So either you make sure you also send a end of line char or your server wait's for something else as "delimiter"
You're reading a line but you aren't writing a line. Add a line terminator to the sent message. Otherwise readLine() won't return until the peer closes the connection.
NB The I/O in the try block after the accept should be in the Runnable, not where it is. Don't do I/O in the accept loop.
How do you code a chat client so that it listens for input both from the server and from the console? This is my current client which successfully sends to and accepts input from the server. As you can see, it doesn't have any code that will enable it to successfully listen for and accept input from the console while also being open to input from the server. The server input would be messages from other chat clients. A message sent from any chat client is broadcast to all other clients. I am pretty new to Java and am completely stuck even though I have a feeling the answer will be depressingly obvious.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClientMain
{
public static void main(String[] args) throws UnknownHostException, IOException
{
//DNS of Chat Server
final String HOST = "localhost";
//Port number for chat server connection
final int PORT = 6789;
Socket serverSocket = new Socket(HOST, PORT);
try
{
//Will need three streams for communication: console-client, client-server, server-client
PrintWriter toServer = new PrintWriter(serverSocket.getOutputStream(), true);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
//User must be logged in; any username is acceptable
System.out.print("Enter username > ");
toServer.println("LOGIN " + fromUser.readLine());
String serverResponse = null;
while((serverResponse = fromServer.readLine()) != null)
{
System.out.println("Server: " + serverResponse);
if(serverResponse.equals("LOGOUT"))
{
System.out.println("logged out.");
break;
}
System.out.print("command> ");
toServer.println(fromUser.readLine());
}
toServer.close();
fromServer.close();
fromUser.close();
serverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
If your main thread is listening to the input from the server, you may start another thread that would keep listening for input from the console. You will have to ensure that you handle input properly. Some flag may be set to indicate if the input is from the server or from the console.