This is my first time using Sockets in any programming language (I'm not familiar with the subject at all) and I'm having a hard time understanding how to send data from different places of code.
Okay I'm running a ServerSocket, and I want to send data from another place in my code rather than the ServerSockets class. How can I do that?
Here's my code:
Server.java
package socket;
import database.models.PersoanaEntity;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static final int PORT = 27015;
public void start() {
new Thread(() -> {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
Socket clientSocket = null;
PersoanaEntity loggedInPerson = new PersoanaEntity();
boolean isClose = false;
System.out.println("Server is running");
while (!isClose) {
clientSocket = serverSocket.accept();
new Thread(new ServerThread(clientSocket)).start();
}
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
ServerThread.java
package socket;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ServerThread extends Thread{
private Socket socket = null;
private ObjectInputStream in = null;
private ObjectOutputStream out = null;
public ServerThread(Socket socket) {
this.socket = socket;
try {
//For receiving and sending data
this.in = new ObjectInputStream(socket.getInputStream());
this.out = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String recievedData = this.in.readObject().toString();
JSONObject jsonObject = new JSONObject(recievedData);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private void sendMessage(String message) {
try {
this.out.writeObject(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Let's say I want to call sendMessage from other classes inside my project. Is there any way to do that?
Thanks!
Keep a reference to the ServerThread object and change the visibility of sendMessage to public. Then it can be called from anywhere.
Aside: Since ServerThread extends Thread, you don't need to wrap it in a new Thread like this new Thread(new ServerThread(clientSocket)).
Related
as I said, i'm tring to do a chat for sevral clients, and one server in java. However, it seems that only one client at the time can connect on the server, and I really don't know why (i'm a begginer in this field).
I have 4 classes, here are they :
MainClient :
package Multicast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MainClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)){
BufferedReader input = new BufferedReader(new java.io.InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
String userInput;
String reponse;
String clientName = "none";
ClientThread clientThread = new ClientThread(socket);
clientThread.start();
do {
if(clientName.equals("none")) {
System.out.println("please enter your name");
userInput = scanner.nextLine();
clientName = userInput;
output.println(userInput);
}
else {
String message = ("|"+clientName +"| :");
//System.out.println(message);
userInput = scanner.nextLine();
output.println(message + " " + userInput);
if (userInput.equals("exit")) {
break;
}
}
}while (!userInput.equals("exit"));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClientThread :
package Multicast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ClientThread extends Thread{
private Socket socket;
private BufferedReader input;
public ClientThread(Socket s) throws IOException {
this.socket = s;
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
#Override
public void run() {
try {
while(true) {
String reponse = input.readLine();
System.out.println(reponse);
}
}
catch(IOException e){
e.printStackTrace();
}
finally {
try {
input.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
MainServer :
package Multicast;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class MainServeur {
public static void main(String[] args) {
ArrayList<ServerThread> threadList = new ArrayList<>();
try(ServerSocket serverSocket = new ServerSocket(5000)){
Socket socket = serverSocket.accept();
ServerThread serverThread= new ServerThread(socket, threadList);
threadList.add(serverThread);
serverThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and ServerThread :
package Multicast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ServerThread extends Thread{
private Socket socket;
private ArrayList<ServerThread> threadList;
private PrintWriter output;
public ServerThread(Socket socket, ArrayList<ServerThread> threads) {
this.socket = socket;
this.threadList = threads;
}
#Override
public void run() {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
while(true) {
String outputString = input.readLine();
if(outputString.equals("exit")) {
break;
}
printToAllClients(outputString);
System.out.println("Server received : " + outputString);
}
}
catch(Exception e) {
System.out.println("error occured in main of server : "+ e.getStackTrace());
}
}
private void printToAllClients(String outputString) {
for(ServerThread sT : threadList) {
sT.output.println(outputString);
}
}
}
when i try to connect a second client, this error occurs :
java.net.BindException: Cannot assign requested address: connect
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:579)
at java.base/sun.nio.ch.Net.connect(Net.java:568)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:633)
at java.base/java.net.Socket.connect(Socket.java:583)
at java.base/java.net.Socket.<init>(Socket.java:507)
at java.base/java.net.Socket.<init>(Socket.java:287)
at Multicast.MainClient.main(MainClient.java:13)
I followed this tutorial, thanks a lot and sorry if the post is too long.
Edit : My problem is solved, here are the changes :
package Multicast;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class MainServeur {
public static void main(String[] args) {
ArrayList<ServerThread> MyThread = new ArrayList<>();
try (ServerSocket serverSocket = new ServerSocket(5000)) {
for (;;) {
Socket socket = serverSocket.accept();
ServerThread s = new ServerThread(socket, MyThread);
MyThread.add(s);
s.start();
}
} catch (IOException e) {
e.printStackTrace();;
}
}
}
You should have one ServerSocket that accepts one client after another in a loop,
on the specified port 5000.
The session then is handled in an other thread, so the next client can be accepted (waited upon).
public class MainServeur {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
for (;;) {
Socket socket = serverSocket.accept();
new ServerThread(socket).start();
}
} catch (IOException e) {
System.getLogger(MainServeur.class.getName()).error(e);
}
}
}
Rather than elementary using a Thread, you can use ExecutorServices.
ThreadPoolExecutor executor = (ThreadPoolExecutor) executors.newFixedThreadPool(50);
That goes beyond the question asked, but allows thread pools limiting the number of clients, wait for all threads to end and more.
I have to do a project in Java for an exam which has to have multi-client sockets.
We have some example code for sockets from our teacher - and I modified it a bit. The problem is that it only receives data once, and then it stops. I found that out by printing the received data into the console.
So here's my the code:
Server.java
package socket;
import database.models.PersoanaEntity;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static final int PORT = 27015;
public void start() {
new Thread(() -> {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
Socket clientSocket = null;
boolean isClose = false;
System.out.println("Server is running");
while (!isClose) {
clientSocket = serverSocket.accept();
new Thread(new ServerThread(clientSocket)).start();
}
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
ServerThread.java
package socket;
import database.models.PersoanaEntity;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ServerThread extends Thread{
private Socket socket = null;
private ObjectInputStream in = null;
private ObjectOutputStream out = null;
PersoanaEntity loggedInPerson = new PersoanaEntity();
public ServerThread(Socket socket) {
this.socket = socket;
try {
//For receiving and sending data
this.in = new ObjectInputStream(socket.getInputStream());
this.out = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String received = this.in.readObject().toString();
System.out.println(received);
JSONObject jsonObject = new JSONObject(received);
execute(received);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private void execute(String message) {
JSONObject jo = new JSONObject(message);
ProcessInput pi = new ProcessInput();
pi.processInput(jo, this.out);
}
}
ProcessInput.java
package socket;
import database.daos.PersoanaDao;
import database.models.PersoanaEntity;
import jakarta.persistence.NoResultException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Optional;
public class ProcessInput {
void processInput(JSONObject data, ObjectOutputStream out) {
switch (data.get("type").toString())
{
case "LOGIN_USER":
PersoanaDao persoanaDao = new PersoanaDao();
String username = data.get("username").toString();
JSONObject json = new JSONObject();
try {
PersoanaEntity persoanaEntity = persoanaDao.get(username);
json.put("status_code", "200");
} catch(Exception e) {
json.put("status_code", "404");
}
try {
out.writeObject(json.toString());
} catch (IOException e)
{
System.out.println(e.toString());
}
break;
}
}
}
I won't add the code from the client side because I'm quite sure the problem is from the server after doing some tests. I think that it happens because the run method is only called once, AFAIK, and that is when .start() is called from the Thread.
Then it won't ever be called again so there will never be data in the received string.
Am I right?
If so, what's the fix?
If not, why am I getting data only once and how can I fix it?
//edit: I will add the client just in case:
package socket;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
public enum Client implements Runnable {
INSTANCE;
public static final int PORT = 27015;
public Socket getSocket() {
return socket;
}
public ObjectInputStream getInputStream() {
return inputStream;
}
public ObjectOutputStream getOutputStream() {
return outputStream;
}
private Socket socket = null;
private ObjectInputStream inputStream = null;
private ObjectOutputStream outputStream = null;
private String name;
Client() {
try {
socket = new Socket("localhost", PORT);
this.outputStream = new ObjectOutputStream(socket.getOutputStream());
this.inputStream = new ObjectInputStream(socket.getInputStream());
} catch(Exception e) {
System.out.println("Connection error");
}
}
public void run() {
System.out.println("Client socket running");
//For receiving data
boolean isClose = false;
while (!isClose) {
}
try {
socket.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I'm trying to do a simple group chat where there's a server and several clients.
The objective is when a client sends a message to the server, the server just sends that message back to all the other clients. I had the server send a message writen by him send to all the clients but he didn't send the clients message.
Server code:
package Group;
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.*;
public class GroupServer extends Thread {
private ServerSocket server;
protected List<ClientHandler> clients;
public static void main(String[] args) throws IOException {
new GroupServer(9876);
}
public GroupServer(int port) {
try {
this.server = new ServerSocket(port);
System.out.println("New server initialized!");
clients = Collections.synchronizedList(new ArrayList<ClientHandler>());
this.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
Socket client = server.accept();
System.out.println(client.getInetAddress().getHostName() + " connected");
ClientHandler newClient = new ClientHandler(client);
clients.add(newClient);
new SendMessage(clients);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class ClientHandler {
protected Socket client;
protected PrintWriter out;
protected DataInputStream in;
public ClientHandler(Socket client) {
this.client = client;
try {
this.out = new PrintWriter(client.getOutputStream());
this.in = new DataInputStream(client.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SendMessage extends Thread {
protected List<ClientHandler> clients;
protected String userInput;
protected String sendMessage;
protected BufferedReader stdIn;
protected DataInputStream in;
public SendMessage(List<ClientHandler> clients) {
this.clients = clients;
this.userInput = null;
this.start();
}
public void run() {
System.out.println("New Communication Thread Started");
if (clients.size() == 1) {
System.out.println("Enter message:");
}
try {
if (clients.size() > 0) {
this.stdIn = new BufferedReader(new InputStreamReader(System.in));
while ((this.userInput = stdIn.readLine()) != null) {
if (userInput != null & userInput.length() > 0) {
for (ClientHandler client : clients) {
sendMessage = client.in.readUTF();
client.out.println(sendMessage);
client.out.flush();
Thread.currentThread();
Thread.sleep(1 * 1000);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The client code:
package Group;
import java.net.*;
import java.io.*;
import java.util.logging.*;
public class GroupClient {
protected Socket client;
protected BufferedReader in;
public static void main(String[] args) {
new GroupClient("Localhost", 9876);
}
public GroupClient(String hostName, int ip) {
try {
this.client = new Socket(hostName, ip);
this.in = new BufferedReader(new InputStreamReader(
this.client.getInputStream()));
String buffer = null;
while ((buffer = in.readLine()) != null) {
System.out.println(buffer);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think the error is in the Server, more preciselly on the SendMessage class.
Thank you for the attention.
You have just one thread "SendMessage" for all the clients.
The very first time you call client.in.readUTF() in a loop, the thread blocks till that client has sent something. Since all the other clients are handled by the same thread. All of them are blocked too.
Either you have one thread per client socket or go the nio selector way (preferrable).
Also fix the issues mentioned by #jingx.
For synchronized arraylist, use CopyOnWriteArrayList. It is specifically meant for these kind of usecases. Synchronization help in concurrent addition and deletion but not during concurrent iteration. CopyOnWriteArrayList solves that problem.
I have a server that accepts sockets from whenever a client connects. I want to be able to shutdown my local server and let my client try to reconnect for about 5 times, and if I start my server the client should indicate that you have reconnected again.
I understand somewhat that this is done in the try{} catch(IOException){Here goes the code for handleing reconnect} I want to use the same socket that I first used to connect. I don't want to create a new Client cause then I have to enter username and stuff like that all over again
I tried to creating a new socket like clientSocket = new Socket("localhost", portnr) but I don't know if this is the correct way to go. If you have examples that answers this please link them. I dont mind reading as long as it is good documented. Thanks in advance!
EDIT.
Here is my Client Class
public class Client {
public static void main(String[] args) {
Client client = new Client();
client.connect();
}
//------------------------------------------------------------
//METHOD CONNECT
//------------------------------------------------------------
private void connect(){
int reConnectTries = 0;
Socket clientsocket;
try {
//------------------------------------------------
//Sets up variables needded for execution
clientsocket = new Socket("localhost", 8900);
DataOutputStream OUT = new DataOutputStream(clientsocket.getOutputStream());
ListenforMessages listen = new ListenforMessages(clientsocket);
//We don't want to enter username all the time
//So this goes not in the while-loop
//------------------------------------------------
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter username");
String username = keyboard.nextLine();
//Sends username to sever so it can be added to a list
OUT.writeUTF(username);
//------------------------------------------------
//------------------------------
//Creates a thread to listen on messages from server(Other clients in this case)
Thread trd = new Thread(listen);
trd.start();
//------------------------------
while (true) {
try {
String sendMessage = keyboard.nextLine();
OUT.writeUTF(sendMessage);
OUT.flush();
} catch (Exception e) {
System.err.println("Could not send message to server. " + e);
}
}
} catch (IOException e) {
System.err.println("Couldnt establish a connection: " + e);
}
}
//------------------------------------------------------------
//CLASS FOR HANDLEING INPUT. We create a class for input on a new thread
//This is cause we don't want it to block other processes.
//----------------------------------------------------------------
class ListenforMessages implements Runnable{
Socket mySocket;
DataInputStream IN;
public ListenforMessages(Socket X) throws IOException {
this.mySocket = X;
}
#Override
public void run() {
try {
IN = new DataInputStream(mySocket.getInputStream());
while (true) {
System.out.println(IN.readUTF());
}
} catch (Exception e) {
System.err.println("Couldn't fetch message from server.Error: " + e);
}
}
}
}
There's a couple of solutions to this problem, but a simple one would to be have the client try to reconnect (open a new connection to the server) at set intervals. For example, you could try something like this to have your client try to reconnect once every 3 minutes:
while(true) {
try {
clientSocket = new Socket("localhost", portnr);
break; // We connected! Exit the loop.
} catch(IOException e) {
// Reconnect failed, wait.
try {
TimeUnit.MINUTES.sleep(3);
} catch(InterruptedException ie) {
// Interrupted.
}
}
}
This way, the client will try to connect, and if it fails, wait for 3 minutes before trying again.
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.NoRouteToHostException;
import java.net.SocketAddress;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.net.ConnectException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
final class TCPClient{
private static Scanner in ;
private static DataOutputStream douts;
private static OutputStream outs;
private static InputStream ins;
private static DataInputStream dins;
private static String ip;
private static Integer port;
private int count = 0;
private static int times;
public TCPClient(){
serverConTest(port);
}
private boolean portIsOpenOrNot(String ip, int port){
try{
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip,port),500);
socket.close();
return true;
}catch(Exception e){
}
return false;
}
private void serverConTest(int port){
while(true){
try{
InetAddress addr = InetAddress.getByName(ip);
SocketAddress sockaddr = new InetSocketAddress(addr,port);
Socket socket = new Socket();
System.out.println("Connecting To server...");
socket.connect(sockaddr);
Thread.sleep(1000);
boolean isactive = true;
if(portIsOpenOrNot(ip,port)){
outs = socket.getOutputStream();
douts = new DataOutputStream(outs);
System.out.println("Sending Request to server:");
while(isactive){
Thread.sleep(1000);
douts.writeUTF("Are you Alive..!");
ins = socket.getInputStream();
dins = new DataInputStream(ins);
System.out.println("Response from server : "+dins.readUTF());
}
}
}catch(SocketException e){
System.out.println("Connection lost");
}catch(IOException e){
break;
}catch(InterruptedException e){
System.out.print("connection timeout in 50 second.");
break;
}
}
}
public static void main(String[] args){
in = new Scanner(System.in);
System.out.print("Enter ip : ");
ip = in.nextLine();
System.out.print("Enter Port : ");
port = Integer.parseInt(in.next());
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future future = executorService.submit(new Runnable() {
public void run() {
new TCPClient();
}
});
try{
future.get(50, TimeUnit.SECONDS);
}catch(InterruptedException e){
}catch(ExecutionException e){
}catch(TimeoutException e){
executorService.shutdownNow();
}
}
}
This sample will give you the complete understanding that when the server restarts then client will reconnects.
I didnt read all your code but this one is working for me
And dont forget to add the Server class and the method send that sends messages...
Client :
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
static Socket sock=null;
static DataInputStream in=null;
static DataOutputStream out=null;
static boolean connected=false;
static String currentip="";
static int currentport=0;
static void refreching(){
try {
in=new DataInputStream(sock.getInputStream());
out=new DataOutputStream(sock.getOutputStream());
Thread gg=new Thread() {
String msg="";
public void run() {
while(connected) {
try {
msg=in.readUTF();
System.out.println(msg);
} catch (IOException e) {
connected=false;
System.out.println("Reconnecing...");
while(!connected)
connect(currentip,currentport);
}
}
}
};
gg.start();
}
catch(Exception e) {
System.out.println("Problem while reading incoming and outgoing"+
"messages!");
connected=false;
}
}
static void connect(String iphost, int port){
try{
sock=new Socket(iphost,port);
currentip=iphost;
currentport=port;
connected=true;
refreching();
System.out.println("Connected!");
}
catch(Exception e){
System.out.println("Cant connect !");
connected=false;
}
}
public static void main(String[] args) {
connect("127.0.0.1",1234); //Example you can enter another's computer ip
//adress if connected to the same network !!!
//Send(Message_To_Server); Dont forget to add the sending code!!!
//Maybe i'll upload a video one day==>how to create a chat application
}
I want to made a Server Which makes a client and start conversation with him but IOException is occur in Handler's code I couldn't underStand why Br.readLine method throws Exception
Here is code of mine Server project's package's classess and two clients abc, def classes are also
This is code of Server projects classeess...............
package server;
import java.io.IOException;
import java.net.ServerSocket;
public class Server {
private void operate() {
try {
ServerSocket serverSocket = new ServerSocket(2222);
while(true) new Thread(new Handler(serverSocket.accept())).start();
} catch(IOException e){
System.out.println("IOException in operate method of Server");
}
}
public static void main(String[] args) {
new Server().operate();
}
}
package server;
import java.io.*;
import java.net.Socket;
public class Handler implements Runnable {
Handler(Socket s) {
socket = s;
counter++;
}
public void run() {
try {
while(true) System.out.println(new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine()); //This throw the IOExceptionnnnnnnnnnnnnnnnnnnnn...............
} catch(IOException e) {
System.out.println("IOException in "+counter+"'s run method");
}
}
private final Socket socket;
private static int counter =0;
}
Code of First Client ABC...........................
package abc;
import java.net.Socket;
import java.io.*;
public class Abc {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost",2222);
while(true) new PrintWriter(socket.getOutputStream()).println("HI from Abc");
} catch(IOException e) {
System.out.println("IOException in main ");
}
}
}
Code of Another Client DEf.........................
package def;
import java.io.*;
import java.net.Socket;
public class DEf {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost",2222);
while(true) new PrintWriter(socket.getOutputStream()).println("HI from Abc");
} catch(IOException e) {
System.out.println("IOException in main ");
}
}
}
Your clients request the output stream repeatedly from the socket using socket.getOutputStream(). Instead, you should invoke this method and create a corresponding writer only once, for example:
Socket socket = new Socket("localhost",2222);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
while(true) {
writer.println("HI from Abc");
...
}
Same with the Handler class - create your buffered reader once.
I have already posted answers on Server-Client Socket Communication. Please have a look.
Java Server with Multiclient communication.
Basic echo server, client-server relationship
Try this code. It might solve you problem.
Handler.java:
Check BufferedReader.ready() before BufferedReader.readLine()
Use single BufferedReader
class Handler implements Runnable {
private BufferedReader reader;
Handler(Socket s) {
socket = s;
counter++;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
while (socket.isConnected() && !socket.isClosed()) {
if(!reader.ready()){
continue;
}
//System.out.println("ready");
System.out.println(reader.readLine()); // This throw
// the
} // IOExceptionnnnnnnnnnnnnnnnnnnnn...............
} catch (Exception e) {
e.printStackTrace();
System.out.println("IOException in " + counter + "'s run method");
}
}
private final Socket socket;
private static int counter = 0;
}
Abc.java:
Use single PrintWriter
PrintWriter writer = new PrintWriter(socket.getOutputStream());
while (true)
writer.println("HI from Abc");
DEf.java:
Use single PrintWriter
PrintWriter writer = new PrintWriter(socket.getOutputStream());
while (true)
writer.println("HI from Abc");