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());
}
}
}
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.
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)).
I wrote a Simple Server Client Program and when I start the Server and the Client, the Client gets the message which it sent to the Server back and terminates itself. But when i start another Client it does not get the message back. Why?
Thanks alot!
First class: the client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class StringClient {
public static void main(String[] args) {
Socket socket = null;
try{
socket = new Socket("localhost", 3141);
OutputStream raus = socket.getOutputStream();
PrintStream ps = new PrintStream(raus, true);
System.out.println("1");
ps.println("Hello World!");
ps.println("Hello Universe!");
InputStream rein = socket.getInputStream();
System.out.println("verf\u00FCgbare Bytes: " + rein.available());
BufferedReader br =new BufferedReader(new InputStreamReader(rein));
System.out.println(2);
while(br.ready()){
System.out.println(br.readLine());
}
}catch(UnknownHostException e ){
System.out.println("Unknown Host...");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOProbleme...");
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
System.out.println("Socket geschlossen...");
}catch(IOException e){
System.out.println("Fehler beim Schließen des Sockets!");
e.printStackTrace();
}
}
}
}
}
Second class: the Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class StringServer {
private final ServerSocket server;
public StringServer(int port) throws IOException {
server = new ServerSocket(port);
}
private void connect(){
while(true){
Socket socket = null;
try{
socket = server.accept();
reinRaus(socket);
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
private void reinRaus(Socket socket) throws IOException{
BufferedReader rein = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream raus = new PrintStream(socket.getOutputStream());
String s;
while(rein.ready()){
s = rein.readLine();
raus.println(s);
}
}
public static void main(String[] args) throws IOException {
StringServer server = new StringServer(3141);
server.connect();
}
}
The main thread should allocates individual/different threads to the incoming clients, so different clients get allocated for different threads (they get different sockets). In your current code there's only a server serving a client.
StringServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class StringServer {
private final ServerSocket server;
public StringServer(int port) throws IOException {
server = new ServerSocket(port);
}
private void connect(){
while(true){
Socket socket = null;
try{
socket = server.accept();
clientHandler ch = new clientHandler(socket);
ch.start();
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws IOException {
StringServer server = new StringServer(3541);
server.connect();
}
}
class clientHandler extends Thread {
Socket client;
public clientHandler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
BufferedReader rein = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream raus = new PrintStream(client.getOutputStream(),true);
String s;
while(rein.ready()){
s = rein.readLine();
raus.println(s);
}
client.close(); // IOException
} catch (IOException e) {
}
}
}
StringClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class StringClient {
public static void main(String[] args) {
Socket socket = null;
try{
socket = new Socket("localhost", 3541);
OutputStream raus = socket.getOutputStream();
PrintStream ps = new PrintStream(raus, true);
System.out.println("1");
ps.println("Hello World!");
ps.println("Hello Universe!");
InputStream rein = socket.getInputStream();
System.out.println("verf\u00FCgbare Bytes: " + rein.available());
BufferedReader br =new BufferedReader(new InputStreamReader(rein));
System.out.println(2);
while(br.ready()){
System.out.println(br.readLine());
}
}catch(UnknownHostException e ){
System.out.println("Unknown Host...");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOProbleme...");
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
System.out.println("Socket geschlossen...");
}catch(IOException e){
System.out.println("Fehler beim Schließen des Sockets!");
e.printStackTrace();
}
}
}
}
}
for an exam i have to make a synchronous multiplayergame, to practice with the serverside, i decided to make a little sketch in processing where two clients exchange the mouse's positions.
The idea is when two client are connected to the server, the server spawn a thread with the two connections, in the thread client send his data to server and server turn the data to the client, so the server is a simple bridge for the clients.
This is the Java server code:
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ProvaServerGioco {
public final static int PORT = 31946;
public final static int MAXPARTITE = 50;
private Socket player1;
private Socket player2;
public final static char separatore = '\n';
public static final String INDIRIZZOHAMACHI = "25.166.111.50";
public static final String INDIRIZZOLAN = "192.168.1.65";
public void start() throws UnknownHostException {
ExecutorService pool = Executors.newFixedThreadPool(MAXPARTITE);
StringBuilder mouse=new StringBuilder();
InetAddress addr = InetAddress.getByName(INDIRIZZOHAMACHI);
try (ServerSocket server = new ServerSocket(PORT, 0, addr)) {
while (true) {
{
if (player1 == null) {
try {
player1 = server.accept();
System.out.println("Ryu");
Writer out = new OutputStreamWriter(
player1.getOutputStream());
out.write("in attesa di giocatore 2" + separatore);
out.flush();
} catch (IOException ex) {
player1.close();
player1 = null;
}
}
if (player2 == null) {
try {
player2 = server.accept();
System.out.println("Ken");
Writer out = new OutputStreamWriter(
player2.getOutputStream());
out.write("in attesa di giocatore 2" + separatore);
out.flush();
} catch (IOException ex) {
player2.close();
player2 = null;
}
}
if(!checkConnessione(player1))
player1=null;
if(!checkConnessione(player2))
player2=null;
if (player2 != null && player1 != null) {
pool.submit(new ThreadPartita(player1, player2));
player1 = null;
player2 = null;
}
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
private boolean checkConnessione(Socket player) {
if (player != null)
try {
Writer out = new OutputStreamWriter(player.getOutputStream());
out.write(separatore);
out.flush();
return true;
} catch (IOException ex) {
try {
player.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
return false;
}
public static void main(String[] args) {
ProvaServerGioco server = new ProvaServerGioco();
try {
server.start();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
And this is the thread for the match:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.util.concurrent.Callable;
public class ThreadPartita implements Callable<Void>{
private Socket player1;
private Socket player2;
private Writer player1Out;
private Writer player2Out;
private BufferedReader readerPlayer1;
private BufferedReader readerPlayer2;
private boolean finePartita=false;
public ThreadPartita(Socket player1,Socket player2)
{
this.player1=player1;
this.player2=player2;
}
#Override
public Void call() throws Exception {
notificaConnessione(player1);
notificaConnessione(player2);
player1Out=new OutputStreamWriter(
player1.getOutputStream());
player2Out=new OutputStreamWriter(
player2.getOutputStream());
readerPlayer1=new BufferedReader(new InputStreamReader(player1.getInputStream(), "ASCII"));
readerPlayer2=new BufferedReader(new InputStreamReader(player2.getInputStream(), "ASCII"));
String mousePlayer1="";
String mousePlayer2="";
while(true&&!finePartita)
{
mousePlayer2=readerPlayer2.readLine();
mousePlayer1=readerPlayer1.readLine();
player1Out.write(mousePlayer2+ProvaServerGioco.separatore);
player1Out.flush();
System.out.println(mousePlayer1);
System.out.println(readerPlayer2.ready());
player2Out.write(mousePlayer1+ProvaServerGioco.separatore);
player2Out.flush();
}
return null;
}
private void inviaMessaggio(Socket player,String messaggio)
{
try{
Writer out = new OutputStreamWriter(
player.getOutputStream());
out.write(messaggio);
out.flush();
}
catch(IOException ex)
{
System.out.println("partita annullata");
}
}
private void notificaConnessione(Socket player)
{
inviaMessaggio(player,"Sei connesso"+ProvaServerGioco.separatore);
}
}
The problem in this code is when i read the data from the player2 in ThreadPartita:
mousePlayer2=readerPlayer2.readLine();
In this line the program freezes, if i comment that line everything is working and player1 send his data to player2 correctly.
I know for sure that is a noob error, but i don't know how to fix it cause i'm a beginner with server socket (i'am studyng the book "java network programming" from o'Reilly in this days).
I don't know if can be useful, but this is the code in processing for the clientside:
import java.net.*;
import java.io.*;
import java.io.Writer;
StringBuilder mouse;
final static int PORTA=31946;
//final static int PORTA=13;
String mouseStringa;
String hamachiIP="127.0.0.1";
Socket socket;
Writer out;
BufferedReader reader;
void setup()
{
size(800,800);
try{
socket = new Socket(hamachiIP, PORTA);
socket.setSoTimeout(15000);
out=new OutputStreamWriter(
socket.getOutputStream());
InputStream in = socket.getInputStream();
mouse = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(in, "ASCII"));
mouseStringa=reader.readLine();
}
catch (IOException ex)
{
System.err.println(ex);
}
}
void draw()
{
background(255);
println(mouseStringa);
try{
mouse = new StringBuilder();
if(reader.ready())
{
String appoggio=reader.readLine();
if(appoggio.length()>0)
mouseStringa=reader.readLine();
}
String posizioniMouse=""+mouseX+';'+mouseY+'\n';
out.write(posizioniMouse);
out.flush();
}
catch (IOException ex)
{
System.err.println(ex);
}
frame.setTitle("fps: "+frameRate);
}
Thank you for your attention!
I am working on multi chat in java. I'm kinda new to this socket thing.
There is a problem with my code but I can't find it. I think the problem is in clientSocket.getInputStream(); . I inserted System.out.println before and after this statement. I can't see the second one. It seems that client can connect to port but cannot get inputs from server. If you can help me, I really would be thankful. It has been 3 hours but still I can't find the problem
ClientSide.java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSide
{
public Socket clientSocket;
public ObjectOutputStream outStream;
public ObjectInputStream inStream;
public String receiveMessage=null,sendMessage=null;
public GuiScreen gui;
public void run()
{
try
{
clientSocket = new Socket("localhost", 2222);
inStream = new ObjectInputStream(clientSocket.getInputStream());
outStream = new ObjectOutputStream(clientSocket.getOutputStream());
outStream.flush();
while(true)
{
try
{
receiveMessage = (String)inStream.readObject();
gui.appendMessage(receiveMessage);
}
catch(ClassNotFoundException classNot)
{System.err.println("data received in unknown format");}
}
}
catch(UnknownHostException unknownHost)
{System.err.println("You are trying to connect to an unknown host!");}
catch(IOException ioException)
{ioException.printStackTrace();}
}
public String readMessage()
{
String text = "";
try
{
text = (String)inStream.readObject();
}
catch (ClassNotFoundException | IOException e)
{e.printStackTrace();}
return text;
}
public void sendMessage(String msg)
{
try
{
outStream.writeObject(msg);
outStream.flush();
}
catch(IOException ioException){ioException.printStackTrace();}
}
public ClientSide()
{}
private void showGui()
{
gui = new GuiScreen(this,"Client Side");
}
public static void main(String[] args)
{
ClientSide client = new ClientSide();
client.showGui();
client.run();
}
}
MultiCheatServer.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiChatServer
{
public static ClientThread[] clientThreads = new ClientThread[10];
public static int portNumber = 2222;
public static ServerSocket serverSocket = null;
public static Socket clientSocket = null;
public static void openPort()
{
try
{
serverSocket = new ServerSocket(portNumber);
}
catch (IOException e)
{e.printStackTrace();}
}
public static void connectToClients()
{
while(true)
{
try
{
clientSocket = serverSocket.accept();
}
catch (IOException e)
{e.printStackTrace();}
for(int i = 0; i<=9; ++i)
{
if(clientThreads[i] == null)
{
clientThreads[i] = new ClientThread(clientSocket,clientThreads);
clientThreads[i].start();
break;
}
}
}
}
public static void main(String[] args)
{
openPort();
connectToClients();
}
}
ClientThread.java
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.Socket;
public class ClientThread extends Thread
{
public ObjectInputStream inStream = null;
public ObjectOutputStream outStream = null;
public Socket clientSocket;
public ClientThread[] clientThreads;
public ClientThread (Socket cSocket,ClientThread[] cThreads)
{
clientSocket = cSocket;
clientThreads = cThreads;
}
public void sendMessage(String msg)
{
try
{
outStream.writeObject(msg);
outStream.flush();
}
catch (IOException e)
{e.printStackTrace();}
}
public String readMessage()
{
String text = null;
try
{
text = (String)inStream.readObject();
}
catch (ClassNotFoundException | IOException e)
{e.printStackTrace();}
return text;
}
public void run()
{
String text;
String name;
try
{
inStream = new ObjectInputStream(clientSocket.getInputStream());
outStream= new ObjectOutputStream(clientSocket.getOutputStream());
outStream.flush();
sendMessage("Name:\n");
name = readMessage().trim();
sendMessage("type /quit if you want to quit\n");
for(int i = 0 ; i <=9 ; ++i)
if(clientThreads[i]!=null && clientThreads[i]!=this)
clientThreads[i].sendMessage(name + "has come\n");
while(true)
{
text = readMessage() ;
if(text.startsWith("/quit"))
break;
for(int i = 0; i<=9; ++i)
if(clientThreads[i] != null)
clientThreads[i].sendMessage("<" + name + ">" + text);
}
for(int i = 0 ;i<=9; ++i)
if(clientThreads[i]!=null && clientThreads[i]!=this)
clientThreads[i].sendMessage(name + " has disconnected\n");
sendMessage("Bye\n");
inStream.close();
outStream.close();
for(int i = 0;i<=9;++i)
if(clientThreads[i]==this)
clientThreads[i] = null;
}
catch (IOException e)
{e.printStackTrace();}
}
}
One problem I see is that you have to decide who creates the input stream first, the server or the client.
ObjectInputStream tries to read a serialization header in its constructor, and if the output stream has not written it yet it will wait. Now both client and server are waiting for the other to "speak" first.