I am trying to figure out why I can send messages to the client from the server but when I try the other way around (to send messages from the client to the server) the program halts like it is waiting for some action to happen.
also how to prevent the sockets from being closed immediately.
this is the code:
Client Class
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
Client aClient = new Client();
aClient.run();
}
private Socket socket;
private PrintWriter toServer;
private BufferedReader fromServer;
public void run() {
try {
socket = new Socket("localhost", 9000);
if (socket.isConnected()){
System.out.println("CONNECTED");
}
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer = new PrintWriter(socket.getOutputStream());
toServer.print("hello server");
System.out.print(fromServer.readLine());
toServer.close();
socket.close();
} catch (Exception error) {
System.out.println("CLIENT ERROR: " + error);
}
}
}
Server Class
import java.io.*;
import java.net*;
public class Server {
public static void main(String[] args) {
Server aServer = new Server();
aServer.run();
}
private ServerSocket mainSocket;
private Socket socket;
private PrintWriter toClient;
private BufferedReader fromClient;
public Server(){
try{
mainSocket = new ServerSocket(9000);
}
catch (Exception error){
System.out.print("Error :"+error);
}
}
public void run() {
System.out.println("WAITING FOR CLIENTS");
try {
socket = mainSocket.accept();
if(socket.isConnected()) {
System.out.println("CONNECTED.");
}
fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toClient = new PrintWriter(socket.getOutputStream());
System.out.println(fromClient.readLine());
toClient.print("hello Client");
toClient.close();
}
catch (Exception error) {
System.out.println("SERVER ERROR :" + error);
}
}
}
Add this before toServer.print("hello server"); to Client class. Its read from System.in and send to the Server class:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromUser;
while((fromUser = stdIn.readLine()) != null) {
System.out.println("Client: " + fromUser);
toServer.println(fromUser);
}
And to Server class add this, before System.out.println(fromClient.readLine());, its read line from client and print to System.out:
String inputLineFromClient;
while ((inputLineFromClient = fromClient.readLine()) != null) {
System.out.println(inputLine);
}
Socket not closing before you invoke method close() or occurs some Exception.
your server is not reading anything.
use
fromClient.readLine();
Related
Multiple Clients say(A, B, C, D etc) make connection to one server through same socket. They all send messages to server as and when required. Client messages are sent only to server(and not to other clients). But whenever server sends a message it should be delivered to all the clients. Please help me out jam only able to get server message on only 1 client
//MultithreadedServer.java
package server;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Vector;
public class MultithreadedServer
{
Vector<ClientHandler> clients = new Vector<ClientHandler>();
Vector<String> users = new Vector<String>();
private static ServerSocket servSocket;
private static final int PORT = 1247;
public MultithreadedServer() throws IOException{
servSocket = new ServerSocket(PORT);
while(true) {
Socket client = servSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler handler;
handler = new ClientHandler(client);
clients.add(handler);
}
}
public static void main(String[] args) throws IOException
{
MultithreadedServer ms = new MultithreadedServer();
}
class ClientHandler extends Thread
{
private Socket client;
private BufferedReader in;
private PrintWriter out;
String name,message,response;
public ClientHandler(Socket socket)
{
//Set up reference to associated socket...
client = socket;
try
{
in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
out = new PrintWriter(
client.getOutputStream(),true);
}
catch(IOException e)
{
e.printStackTrace();
}
start();
}
public void sendMessage(String msg) {
System.out.println("is it even coming here?");
out.println("Server:" + msg);
}
public void boradcast(String message) {
// send message to all connected users
for (ClientHandler c : clients) {
c.out.println("Server: hello");
}
}
public String getUserName() {
return name;
}
public void run()
{
try
{
String received;
do
{ System.out.println("Enter Your Message: ");
String msg = in.readLine();
out.println(msg);
boradcast("testing");
received = in.readLine();
out.println("ECHO: " + received);
//Repeat above until 'QUIT' sent by client...
}while (!received.equals("QUIT"));
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (client!=null)
{
System.out.println(
"Closing down connection...");
client.close();
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
}}
//ClientProgram
import java.io.*;
import java.net.*;
public class Client
{
private static InetAddress host;
private static final int PORT = 1247;
private static Socket link;
private static BufferedReader in;
private static PrintWriter out;
private static BufferedReader keyboard;
public static void main(String[] args) throws IOException
{
try
{
host = InetAddress.getLocalHost();
link = new Socket(host, PORT);
in = new BufferedReader(
new InputStreamReader(
link.getInputStream()));
out = new PrintWriter(
link.getOutputStream(),true);
keyboard = new BufferedReader(
new InputStreamReader(System.in));
String message, response;
do
{
System.out.print(
"Enter message ('QUIT' to exit): ");
message = keyboard.readLine();
//Send message to server on
//the socket's output stream...
out.println(message);
//Accept response frm server on
//the socket's input stream...
response = in.readLine();
//Display server's response to user...
System.out.println(response);
}while (!message.equals("QUIT"));
}
catch(UnknownHostException uhEx)
{
System.out.println(
"\nHost ID not found!\n");
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
try
{
if (link!=null)
{
System.out.println(
"Closing down connection...");
link.close();
}
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
}
}
}
An obvious way to do this would be to cycle through all ClientHandlers in clients and send the message to each of them:
for (ClientHandler ch : clients){
ch.sendMessage(message); //Or something
}
A single client connects to a single server.
I'm unable to display the text sent from the client.
Am I not sending the text properly from client or not receiving the text properly on Server?
Is there another way to check from the code? (on client side that the data has been sent) or (on server side that the data has been received)
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class ChatServer {
public static void main(String[] args) throws IOException {
ChatServer chatServer = new ChatServer();
chatServer.go();
}
private void go() throws IOException {
//Generate a random number and write to a text file
Random randomGenerator = new Random();
int randomInt = 1024 + randomGenerator.nextInt(64511);
PrintWriter printWriter = new PrintWriter("port.txt");
printWriter.write(String.valueOf(randomInt));
printWriter.flush();
//Create Server on a port using that random number
ServerSocket serverSocket = new ServerSocket(randomInt);
System.out.println("Server on Port: "+randomInt);
//Start Accepting Clients
ClientHandler clientHandler= new ClientHandler(serverSocket);
Thread t = new Thread(clientHandler);
t.start();
}
private class ClientHandler implements Runnable {
ServerSocket serverSocket;
BufferedReader bufferedReader;
PrintWriter writer;
Socket socket;
public ClientHandler(ServerSocket sSocket) throws IOException {
serverSocket = sSocket;
}
public void run() {
while (true)
{
String message;
try {
//Accept A connection and assign a socket for this client
socket = serverSocket.accept();
System.out.println("Connection Established");
//Read Message
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
while( (message = bufferedReader.readLine()) != null)
{
//Display it on the console
System.out.println("From Client: " + message);
//Send it back to the client
writer = new PrintWriter(socket.getOutputStream());
writer.println("Your message is: " + message);
writer.flush();
//Send your message
writer.write("This is default message");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This is Client Side Code
package com.company;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
Socket socket;
public static void main(String[] args) throws IOException {
ChatClient chatClient = new ChatClient();
chatClient.go();
}
private void go() throws IOException {
//Read Port number from file
FileReader fileReader = new FileReader("port.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int port = Integer.parseInt(bufferedReader.readLine());
//Connect to socket on the port number
System.out.println("Connecting to Server on: "+port);
socket = new Socket("127.0.0.1",port);
//Initiate sender thread
ChatSender chatSender = new ChatSender(socket);
Thread sender = new Thread(chatSender);
//Initiate receiver thread
ChatReceiver chatReceiver = new ChatReceiver(socket);
Thread receiver = new Thread(chatReceiver);
sender.start();
receiver.start();
}
public class ChatSender implements Runnable
{
BufferedWriter bufferedWriter;
public ChatSender(Socket socket) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
bufferedWriter = new BufferedWriter(outputStreamWriter);
}
public void run()
{
while (true)
{
//get text from console
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println("To Server: "+input);
try {
System.out.println("Sending data");
//write to server
bufferedWriter.write(input);
//flush the text
bufferedWriter.flush();
System.out.println("sent data");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ChatReceiver implements Runnable
{
BufferedReader bufferedReader;
public ChatReceiver(Socket socket) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
}
public void run()
{
try {
while (true)
{
Thread.sleep(1000);
System.out.println("Receiving data");
String output = bufferedReader.readLine();
System.out.print("From Server: "+output);
System.out.println("Received data");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Usual problem. You're reading lines, but you aren't sending lines. Change write() to println().
I want to write a client-sever program in which server and client send messages to each other. First, my server send a message to client, then the client reply. Next, my server send another message, the client reply. The problem is, on my first message induced by the server, the client does not respond.
My server:
public class Server {
public void go() {
try {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server listening ...");
Socket socket = serverSocket.accept();
try (
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String input;
printWriter.println(new Scanner(System.in).nextLine());
while ((input = bufferedReader.readLine()) != null) {
System.out.println(input);
printWriter.println(new Scanner(System.in).nextLine());
if(input == "Bye") break;
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.go();
}
}
My client:
public class Client {
public void go() {
try {
try (
Socket socket = new Socket("localhost", 9999);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String input;
while ((input = bufferedReader.readLine()) != null) {
System.out.println("1");
System.out.println(input);
printWriter.println(new Scanner(System.in).nextLine());
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
client.go();
}
}
Are there some problems with my code?
Your client connects and then blocks reading a line from the server.
Your server accepts the connection and then blocks reading a line from the client.
I don't know what you were expecting to happen next, but it won't. Somebody needs to send something.
Your code seems to be fine. You just need to push the infrastructure by calling flush() after writing:
printWriter.flush();
I have a client class and a server class.
If client sends message to server, server will send response back to the client, then client will print all the messages it received.
For example,
If Client sends "A" to Server, then Server will send response to client
"1111". So I use readLine() in client class to read the message from server, then client print "1111" in the console.
If Client sends "B" to Server, then Server will send response to client
"2222\n 3333". So the expected printing output from client is:
"2222"
"3333"
So the response message from server to client may have 1 line or 2 lines depending on the message it send from client to server.
My question is that how I can use readLine() to read the message that send from server to client. More specifically, if I use the following codes,
String messageFromServer;
while(( messageFromServer = inputStreamFromServer.readLine()) != null) {
println(messageFromServer);
}
It will only print the first line, and will not print anything else even if I keep sending message from client to server, because readLine() will stops once it has read the first line.
update:
More specifically, I am looking for some methods in the client class to read message that contains 1 or multiple lines from server at a time. I am wondering if there are any ways to do it in client side if I don't want to change the format of the message that sent from server to client.
update 2
To make my question more clear, I will put some sample codes in the following:
This is server:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(1234);
} catch (IOException e) {
System.err.println("Could not listen on port: 1234.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
}
System.out.println("Connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String textFromClient =null;
String textToClient =null;
textFromClient = in.readLine(); // read the text from client
if( textFromClient.equals("A")){
textToClient = "1111";
}else if ( textFromClient.equals("B")){
textToClient = "2222\r\n3333";
}
out.print(textToClient + "\r\n"); // send the response to client
out.flush();
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
The client:
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
}
System.out.println("Connected");
String textToServer;
while((textToServer = read.readLine())!=null){
out.print(textToServer + "\r\n" ); // send to server
out.flush();
String messageFromServer =null;
while(( messageFromServer = textToServer=in.readLine()) != null){
System.out.println(messageFromServer);
}
}
out.close();
in.close();
read.close();
socket.close();
}
private static void debug(String msg)
{
System.out.println("Client: " + msg);
}
}
You shouldn't need to change the format of the data sent by the server, and readLine() should work, but I suspect that the server is not flushing or closing the OutputStream after writing the response which could possibly explain things.
Is the call to readLine() hanging? Are you in control of the server code? If so, can you include it?
Revised classes that work as I believe you expect:
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 ClientServerTest2
{
public static void main(String[] args) throws Exception
{
Thread serverThread = new Thread(new Server());
serverThread.start();
Thread clientThread = new Thread(new Client());
clientThread.start();
serverThread.join();
clientThread.join();
}
private static class Server implements Runnable
{
#Override
public void run()
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(1234);
Socket clientSocket = null;
clientSocket = serverSocket.accept();
debug("Connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String textFromClient = null;
String textToClient = null;
textFromClient = in.readLine(); // read the text from client
debug("Read '" + textFromClient + "'");
if ("A".equals(textFromClient))
{
textToClient = "1111";
}
else if ("B".equals(textFromClient))
{
textToClient = "2222\r\n3333";
}
debug("Writing '" + textToClient + "'");
out.print(textToClient + "\r\n"); // send the response to client
out.flush();
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void debug(String msg)
{
System.out.println("Server: " + msg);
}
}
private static class Client implements Runnable
{
#Override
public void run()
{
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try
{
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
debug("Connected");
String textToServer;
textToServer = read.readLine();
debug("Sending '" + textToServer + "'");
out.print(textToServer + "\r\n"); // send to server
out.flush();
String serverResponse = null;
while ((serverResponse = in.readLine()) != null)
debug(serverResponse); // read from server and print it.
out.close();
in.close();
read.close();
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private static void debug(String msg)
{
System.out.println("Client: " + msg);
}
}
Change while(( messageFromServer = inputStreamFromServer.readLine() != null) to while(( messageFromServer = inputStreamFromServer.readLine()) != null)
Actually this shouldn't even compile....
It's a work around.
If you want to send multiple strings like in your case : "2222\n 3333".
You can send them by adding a seperator character (like :) between two strings : "2222: 3333".
Then you can call write from server side as
clientOut.write("2222: 3333\n");
On client side parse recieved String :
messageFromServer = inputStreamFromServer.readLine();
String strArray[] = messageFromServer.split(":");
strArray[0] : 2222
strArray[0] : 3333
I am working on a java socket program and have difulcites with the client part. The server get's what all the clients write, but the client only gets what it writes. Could someone provide me with an example of a client part of a program that gets what all the clients write? Thanks!
Here is an "echo server" example
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws IOException
{
ServerSocket serverSocket = null;
DataInputStream serverInput = null;
PrintStream serverOutput = null;
String line = null;
Socket clientSocket = null;
// create server socket
try
{
serverSocket = new ServerSocket(2012);
clientSocket = serverSocket.accept();
serverInput = new DataInputStream(clientSocket.getInputStream());
serverOutput = new PrintStream(clientSocket.getOutputStream());
}
catch(IOException e){System.out.println(e);}
// receive data and send it back to the client
try
{
while(true)
{
line = serverInput.readLine();
if(line.equals("exit"))
{
break;
}
else
{
if(!line.equals(null) && !line.equals("exit"))
{
System.out.println("Received " +line);
line = line+" MODIFIED";
serverOutput.println(line);
}
}
}
}
catch(IOException e){System.out.println("SERVER SIDE: Unable send/receive data");}
try
{
serverInput.close();
serverOutput.close();
clientSocket.close();
serverSocket.close();
}
catch(IOException e){System.out.println(e);}
}
}
Here is the client
import java.io.*;
import java.net.*;
public class TCPClient
{
public static void main(String[] args) throws IOException
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 2012);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
if(userInput.equals("exit"))
break;
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}