How do I make my chat application continuous? - java

I have to make a chat application that is able to chat continuously back and forth between the server and the client. I have it so that the server and the client can send one message at a time, but I am not sure how to edit my code so that you can send multiple messages at a time. Also, I need to be able to run this on two separate computers, and I think I have my code set up accurately for this, but I am not sure. Verification for this and an answer to the first question would be appreciated. My code for each class is below.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ChatServer{
private ServerSocket serverSocket;
private Socket acceptSocket;
private PrintStream output;
private BufferedReader input;
private Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
ChatServer server = new ChatServer();
server.run();
}
public void run() {
try {
serverSocket = new ServerSocket(9999);
acceptSocket = serverSocket.accept();
output = new PrintStream(acceptSocket.getOutputStream());
input = new BufferedReader(new InputStreamReader(acceptSocket.getInputStream()));
while(acceptSocket.isConnected()) {
String message = input.readLine();
System.out.println(message);
String reply = scan.nextLine();
output.println(reply);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient{
private Socket clientSocket;
private BufferedReader input;
private PrintStream output;
private Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
ChatClient client = new ChatClient();
client.run();
}
public void run() {
try {
clientSocket = new Socket("127.0.0.1", 9999);
output = new PrintStream(clientSocket.getOutputStream());
output.println("Connected to Server");
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(clientSocket.isConnected()) {
String message = input.readLine();
System.out.println(message);
String reply = scan.nextLine();
output.println(reply);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

SocketIO for Java is my suggestion. It does what you need it to in what will likely end up being less code and the documentation on it is superb with lots of examples. There is even an Android app demo that uses it for peer-to-peer chat.
https://github.com/socketio/socket.io-client-java

Related

How do I send objects back and forth continuously across sockets in Java?

What I am trying to do here is create an application that will be a basic game, and first I have to get the networking functional. I'm struggling to send objects back and forth between server and client. The design I am trying to achieve is 2 processes with 2 threads each, the main thread and then a listener thread. I want the listener thread to listen for incoming objects, as this will be used for an event bus. Currently to get it working I'm using just a simple message class which holds a single string field called text. The issue I'm having is that the client listener thread doesn't seem to start, and the objects never get sent either way. Really struggling learning network programming here, any help is much appreciated.
Server side
package Server;
import java.net.*;
import java.util.List;
import Utilities.Message;
import java.io.*;
public class BattleshipServer
{
public static void executeThreadedServer(int port) throws Exception
{
ServerSocket server = new ServerSocket(port);
System.out.println("Awaiting connection");
Socket socket = server.accept();
System.out.println("Connection established");
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
//Start the listener thread
ServerListener sListener = new ServerListener(kb, out, in);
sListener.run();
Message msg = new Message("temp");
while(!msg.getText().equalsIgnoreCase("exit"))
{
msg = new Message(kb.readLine());
out.writeObject(msg);
out.flush();
}
}
}
------------------------------------------------------------------------------------------------------------
package Server;
import java.io.BufferedReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import Utilities.Message;
public class ServerListener implements Runnable
{
private BufferedReader keyBoard;
private ObjectOutputStream out;
private ObjectInputStream in;
public ServerListener(BufferedReader keyboard, ObjectOutputStream out, ObjectInputStream in)
{
this.keyBoard = keyboard;
this.out = out;
this.in = in;
}
#Override
public void run()
{
System.out.println("Server listener started");
try {
while(true)
{
Message msg;
while((msg = (Message)this.in.readObject()) != null)
{
System.out.println(msg.getText());
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Client Side
package Client;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import Utilities.Message;
import java.io.*;
public class BattleshipClient
{
public static void executeThreadedClient(String address, int port) throws Exception
{
Socket socket = new Socket(address, port);
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ClientListener cListener = new ClientListener(kb,out,in);
cListener.run();
Message msg = new Message("temp");
while(!msg.getText().equalsIgnoreCase("exit"))
{
msg = new Message(kb.readLine());
out.writeObject(msg);
out.flush();
}
socket.close();
}
}
------------------------------------------------------------------------------------------------------------
package Client;
import java.io.BufferedReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import Utilities.Message;
public class ClientListener implements Runnable
{
private BufferedReader keyBoard;
private ObjectOutputStream out;
private ObjectInputStream in;
public ClientListener(BufferedReader keyboard, ObjectOutputStream out, ObjectInputStream in)
{
this.keyBoard = keyboard;
this.out = out;
this.in = in;
}
#Override
public void run()
{
System.out.println("Client listener started");
try
{
while(true)
{
Message msg = (Message)in.readObject();
System.out.println(msg.getText());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Although your ClientListener and ServerListeners are implementing Runnable, they are not run in a separate thread. In your implementation, it is just another function call and therefore the code after the listener.run() never gets called.
So instead of doing:
ClientListener cListener = new ClientListener(kb,out,in);
cListener.run();
You need to do something like:
Thread clientThread = new Thread(new ClientListener(kb,out,in));
clientThread.start();
And on the server side you need to do something similar.

How do I get my multithreaded server/client chat program to echo messages to all clients using sockets?

right now I have a java program that uses threads and sockets to echo text responses like a real chat window. Currently, my program works by running the server and than as many clients as I want. When a client enters a message, that message is echoed to the server and also to the client that sent the message.
My problem is that I want the message any client enters to be sent not only to the server and to themselves, but to every other client as well.
Heres how it currently works:
Server:
Received client message: test1
Client 1:
Enter message: test1
test1
Client 2:
Enter message:
Client 1 enters test1, receives test1 back and the server also receives test1. Client 2 gets nothing. My goal is to have any messages entered in the clients display on the client that sent the message as well as the other clients and server.
Working example:
Server:
Received client message: test1
Received client message: hello
Client 1:
Enter message: test1
test1
From client 2: hello
Client 2:
Enter message:
From client 1: test1
hello
The formatting doesnt have to be exactly like that, but thats the idea. My code so far is below. Ive read that I need to add my clients to a list and then loop over them and send them all the message but im not sure. Any help would be great.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Scanner;
public class EchoMultiThreadClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 4000)) {
//socket.setSoTimeout(5000);
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
String echoString;
String response;
do {
System.out.println("Enter string to be echoed: ");
echoString = scanner.nextLine();
pw.println(echoString);
if(!echoString.equals("exit")) {
response = br.readLine();
System.out.println(response);
}
} while(!echoString.equals("exit"));
// }catch(SocketTimeoutException e) {
// System.out.println("The Socket has been timed out");
} catch (IOException e) {
System.out.println("Client Error: " + e.getMessage());
}
}
}
server code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
public class EchoMultiThreadServer {
private static Vector<Echoer> clients = new Vector<Echoer>();
public static void main(String [] args) {
try(ServerSocket serverSocket = new ServerSocket(4000)){
while(true) {
Socket socket = serverSocket.accept();
Echoer echoer = new Echoer(socket);
echoer.start();
clients.add(echoer);
}
}catch(IOException e) {
System.out.println("Server Exception"+e.getMessage());
}
}
}
thread code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Echoer extends Thread{
private Socket socket;
public Echoer(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter wr = new PrintWriter(socket.getOutputStream(), true);
while(true) {
String echoString = in.readLine();
System.out.println("Received Client Input: " + echoString);
if(echoString.equals("exit")) {
break;
}
wr.println(echoString);
}
}catch(IOException e) {
System.out.println("Oooops " + e.getMessage());
}finally {
try {
socket.close();
}catch(IOException e) {
// later
}
}
}
}
I can see two problems with your current logic:
At the client side, you are essentially reading user input, then sending to server and getting a (single) response. So the problem here is that you only get one response, while you should take more than one for each user input line: that is the user's input plus the other users' input. Since you don't know when and how many the other users' inputs are going to be, you need to go asynchronous. I mean that you need 2 threads: one for reading user input and the other for reading server input/response (note: we are still at the client side). Since you already have one of the 2 threads, ie the one which runs the main method, then you can use it instead of creating a new one.
At the server side, your Echoer is reading user input but only sending it back to the same client. You need for example a loop to send the client's input to all other clients too.
So what would seem to me a proper logic is:
Client side:
Reading server's responses thread logic:
forever, do:
get server's message.
print server's message to user.
main method:
connect to server.
start a "Reading server's responses thread".
get user input.
while the user's input it not "exit", do:
send user's input to server.
get user input.
disconnect from server.
Server side:
Echoer thread:
forever, do:
read client's message.
for every client, do:
send the message to the client.
main method:
start server socket.
forever, do:
accept incoming connection.
start an Echoer thread for the accepted connection.
There are some missing bits though, such as how to maintain the list of all clients, but for that I can see you are already using a Vector<Echoer> clients at the server side. So just pass that Vector to every Echoer you create, so they can do the broadcasting of each incomming message. Important note here: at the server side, you have more than one threads: the main one and each Echoer, so make sure you synchronize on the Vector while you are modifying it at the main thread and also while broadcasting at the Echoers.
Notes:
I am assuming in all the above logic that there is no particular order in which the clients send their messages. For example if always client A sent first, then client B and so on, and the whole process was repeating, then you wouldn't need to go multithreading at all.
Please take your time. First implement it and then tell me if you encouter any problems.
Edit 1: full sample code.
Client code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Client {
//This is the "Reading server's responses thread" I am talking about in the answer.
private static class ReadingRunnable implements Runnable {
private final BufferedReader serverInput;
public ReadingRunnable(final InputStream is) {
serverInput = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
}
#Override
public void run() {
try {
//While the server is not disconnected, we print each line to 'System.out':
for (String line = serverInput.readLine(); line != null; line = serverInput.readLine())
System.out.println(line);
}
catch (final IOException iox) {
iox.printStackTrace(System.out);
}
finally {
System.out.println("Input from server stopped.");
}
}
}
public static void main(final String[] args) {
try {
System.out.print("Connecting... ");
try (final Socket sck = new Socket("localhost", 50505);
final OutputStream os = sck.getOutputStream();
final InputStream is = sck.getInputStream()) {
System.out.println("Connected.");
new Thread(new ReadingRunnable(is)).start();
final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
final Scanner scan = new Scanner(System.in);
for (String userInput = scan.nextLine(); !"exit".equalsIgnoreCase(userInput); userInput = scan.nextLine()) {
bw.write(userInput);
bw.newLine();
bw.flush();
}
}
}
catch (final IOException iox) {
iox.printStackTrace(System.out);
}
finally {
System.out.println("Output from user stopped.");
}
}
}
Server code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Objects;
public class Server {
private static class Echoer implements Runnable {
private final ArrayList<Echoer> all;
private final BufferedWriter bw;
private final BufferedReader br;
public Echoer(final ArrayList<Echoer> all,
final InputStream is,
final OutputStream os) {
this.all = Objects.requireNonNull(all);
bw = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
}
//Instead of exposing 'bw' via a getter, I just built a helper method to send a message to the Echoer:
public void send(final String msg) throws IOException {
bw.write(msg);
bw.newLine();
bw.flush();
}
#Override
public void run() {
try {
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line); //Print the received line at the server.
synchronized (all) { //We are reading from a collection which may be modified at the same time by another (the main) Thread, so we need to synchronize.
//Broadcast the received line:
for (int i = all.size() - 1; i >= 0; --i) {
try {
all.get(i).send(line);
}
catch (final IOException iox) {
all.remove(i); //In case we cannot send to the client, disconnect him, ie remove him from the list in this simple case.
}
}
}
}
}
catch (final IOException iox) {
}
finally {
synchronized (all) {
all.remove(this); //Disconnect him, ie remove him from the list in this simple case.
}
System.out.println("Client disconnected.");
}
}
}
public static void main(final String[] args) throws IOException {
System.out.print("Starting... ");
try (final ServerSocket srv = new ServerSocket(50505)) {
final ArrayList<Echoer> all = new ArrayList<>();
System.out.println("Waiting for clients...");
while (true) {
final Socket sck = srv.accept();
try {
final OutputStream os = sck.getOutputStream();
final InputStream is = sck.getInputStream();
final Echoer e = new Echoer(all, is, os); //Pass all the Echoers at the new one.
synchronized (all) { //We will write to a collection which may be accessed at the same time by another (an Echoer) Thread, so we need to synchronize.
all.add(e); //Update list of Echoers.
}
new Thread(e).start(); //Start serving Echoer.
}
catch (final IOException iox) {
System.out.println("Failed to open streams for a client.");
}
}
}
}
}

Why javafx application is crashing while using EventHandler and java.net socket at the same time?

I'm trying to build some Chatting Application with Javafx and java.net networking package. I want the text the User typed in the textfield to be send from the client to the server and from there back to the client and eventually showing up in the textarea of the application. But the application is crashing after I press Enter when I typed in a text in the TextField. So in the "handle"-method of the EventHandler there must be the error. Also the application is crashing before the input-text gets cleared. The application is not responding --> error window pops up.Application is not responding
Client-side Code:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.Parent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.*;
public class ChatAppClient extends Application {
private TextArea messages = new TextArea();
private TextField input;
private static String ipAdress = null;
private DataInputStream dis;
private DataOutputStream dos;
private static Socket client;
public Parent mainScene() throws UnknownHostException, IOException {
// Getting IP-Adress from a different file as a String
String userDir = System.getProperty("user.dir");
File file = new File(userDir + "\\..\\IPAdress.txt");
RandomAccessFile raFile = new RandomAccessFile(file, "rw");
raFile.seek(0);
ipAdress = raFile.readLine();
raFile.close();
// Initialising new Socket
client = new Socket(ipAdress, 5000);
System.out.println("Connected to Server.");
// Defining JavaFx Application-Layout
messages.setPrefHeight(220);
input = new TextField();
VBox root = new VBox(20, messages, input);
root.setPrefSize(400, 400);
// Setting up action for Textfield when pressing Enter
input.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
// Defining and initialising Input-String
String message = "Client: ";
message += input.getText();
// Opening OutputStream for String to send it to the server
dos = new DataOutputStream(client.getOutputStream());
// Giving the String to the OutputStream
dos.writeBytes(message);
// Clearing the Textfield from Input-Text
input.clear();
// Setting up InputStream for the Socket to receive the String back from the
// server
dis = new DataInputStream(client.getInputStream());
// Reading String from InputStream
String s = dis.readLine();
// Closing In-and OutputStreams + Socket
dos.close();
// Showing the String in the TextArea "messages"
messages.appendText(s + "\n");
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
});
return root;
}
public void start(Stage mainStage) {
try {
mainStage.setScene(new Scene(mainScene()));
mainStage.show();
} catch (UnknownHostException uHE) {
uHE.printStackTrace();
} catch (IOException iOE) {
iOE.printStackTrace();
}
}
public static void main(String[] args) {
try {
launch(args);
client.close();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
}
Server-side Code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatAppServer {
public static void main(String[] args) {
try {
// Defining/ Initialising new ServerSocket
ServerSocket caServerSocket = new ServerSocket(5000);
System.out.println("Waiting for Client...");
Socket nSocket = caServerSocket.accept();
System.out.println("Client connected.");
// Setting up InputStream for the ServerSocket to receive the message String
DataInputStream clientMessages = new DataInputStream(nSocket.getInputStream());
String s = clientMessages.readLine();
// Testing if the Input String got received
System.out.println(s);
// Setting up OutputStream to send back the String
DataOutputStream clientMessagesBack = new DataOutputStream(nSocket.getOutputStream());
clientMessagesBack.writeBytes(s);
caServerSocket.close();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
}

Java: Simple Client Server message exchange not working

I am new to Java just started yesterday. I wrote a very simple client server java code. Client sends a message to server. The Server should display that message. And the Server should send a message to client after receiving the message. The client should display the message sent by server.
Server Code,
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.net.Socket;
import java.net.ServerSocket;
public class CustomServer{
public static void main(String[] args){
final int SERVER_PORT_NUMBER = 8081;
try{
ServerSocket serverObj = new ServerSocket(SERVER_PORT_NUMBER);
Socket clientSocketObj = serverObj.accept();
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocketObj.getInputStream()));
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocketObj.getOutputStream()));
if(clientSocketObj != null){
System.out.println("Client Connected to Server!");
// Recieve Message from Client
System.out.println("MESSAGE FROM CLIENT");
System.out.println(clientInputStream.readLine());
// Send Message to Client
clientOutputStream.write("SERVER: Hello Client!");
// Close Streams
clientOutputStream.close();
clientInputStream.close();
}
serverObj.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Client,
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
public class CustomClient{
public static void main(String[] args){
final String HOST_NAME = "127.0.0.1";
final int SERVER_PORT_NUMBER = 8081;
try{
Socket clientSocket = new Socket(HOST_NAME, SERVER_PORT_NUMBER);
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Connecting....");
if(clientSocket != null){
System.out.println("Connected to Server!");
// Send message to Server
clientOutputStream.write("CLIENT: HELLO SERVER");
// Recieve message from Server
System.out.println("MESSAGE FROM SERVER");
System.out.println(clientInputStream.readLine());
// Close Streams
clientInputStream.close();
clientOutputStream.close();
}
clientSocket.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Neither the Server or Client receive the message. Stuck in some loop. Anyone know why?
Start by having a read of the BufferedReader's JavaDocs, which state
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed
BufferedWriter#write is not sending this, so the reader is still waiting.
A simply solution might be to use BufferedWriter#newLine after the write
And don't forget to flush the buffer when you're finished writing to it!
You may also want to take a look at try-with-resources which will provide a better resource management solution
CustomClient
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class CustomClient {
public static void main(String[] args) {
final String HOST_NAME = "127.0.0.1";
final int SERVER_PORT_NUMBER = 8081;
try (Socket clientSocket = new Socket(HOST_NAME, SERVER_PORT_NUMBER)) {
try (BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
System.out.println("Connecting....");
System.out.println("Connected to Server!");
// Send message to Server
clientOutputStream.write("CLIENT: HELLO SERVER");
clientOutputStream.newLine();
clientOutputStream.flush();
// Recieve message from Server
System.out.println("MESSAGE FROM SERVER");
System.out.println(clientInputStream.readLine());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
CustomServer
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class CustomServer {
public static void main(String[] args) {
final int SERVER_PORT_NUMBER = 8081;
try (ServerSocket serverObj = new ServerSocket(SERVER_PORT_NUMBER)) {
try (Socket clientSocketObj = serverObj.accept()) {
try (BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocketObj.getInputStream()));
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocketObj.getOutputStream()))) {
System.out.println("Client Connected to Server!");
// Recieve Message from Client
System.out.println("MESSAGE FROM CLIENT");
System.out.println(clientInputStream.readLine());
// Send Message to Client
clientOutputStream.write("SERVER: Hello Client!");
clientOutputStream.newLine();
clientOutputStream.flush();
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}

Java networking, cant figureout what's wrong with multithread server

my name is Jędrzej and I am new here. I was trying to write a simple chat in java. I am trying to make multithread server so multiple clients can connect to this server. My client works fine, but if I run two clients, they dont see each others responses. Code bellow:`
package serverthread;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerWIthThreads {
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(1234);
while(true){
Socket socket = serverSocket.accept();
Runnable r = new ThreadForServer(socket);
Thread t = new Thread(r);
t.start();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
package serverthread;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ThreadForServer implements Runnable{
private Socket socket;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
public ThreadForServer(Socket i){
socket = i;
}
#Override
public void run(){
try{
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.flush();
while(true){
String message = (String) inputStream.readObject();
outputStream.writeObject(message);
outputStream.flush();
}
}catch(IOException e){
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
`
The way you've implemented this, you're reading a message from one client and then writing it back to the same client.
You'll need to revise your program so that you can write the message to the Socket of the other connected client.

Categories

Resources