There is something wrong with my server (multi client) code...
Basically I wrote a little multi client server and I tested it, it could send and receive strings.
But I did few modifications to make it receive string from the clients and send it to each client and it quite not works well..
Here is the the code that you can copy and paste in ecplice and run it
Server got only one class called "Server" and client got two classes, first class's name is what ever you want and second is "Client"
The main class launches the client class.
I know that you hate long codes, but I can't understand what problem is... I am sorry
Here is the code for the Server:
Code:
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class Server implements Runnable{
public static ArrayList<Socket> clientSock = new ArrayList<Socket>();
public static ServerSocket MSS;
public void start(){
new Thread(this).start();
comm();
}
public static void main(String[] args){
try {
MSS = new ServerSocket(2807);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Server server = new Server();
server.start();
}
public static void waitForConnection(){
try {
System.out.println("Waiting for the connections...");
Socket sock1 = MSS.accept();
clientSock.add(sock1);
System.out.println("Connections: " + clientSock.size());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void comm(){
System.out.println("Starting communication.");
while(true){
for(int i = 0; i<clientSock.size(); i++){
try {
BufferedReader ClientIn;
ClientIn = new BufferedReader(new InputStreamReader(clientSock.get(i).getInputStream()));
String msg = ClientIn.readLine();
if(msg != null){
System.out.println(msg);
for(int c=0; c<clientSock.size(); c++){
try {
PrintStream serverOut;
serverOut = new PrintStream(clientSock.get(c).getOutputStream());
serverOut.print(msg + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void run() {
while(true){
waitForConnection();
}
}
}
For the client:
Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void sockStr(){
String host = "localhost";
int port = 2807;
try{
Socket skt = new Socket(host,port);
BufferedReader serverIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintStream clientOut = new PrintStream(skt.getOutputStream());
clientOut.print("SUUCCESSSS \n");
while(true){
String msg = serverIn.readLine();
if(msg != null){
System.out.println(msg);
msg = null;
}
}
}catch (Exception e){}
}
}
How ever when I add Code:
System.out.println("test");
inside of the while loop in the "comm()" method, it spamming "test" until the client connects to the server and It is received and sent the string like I wanted BUT it stopped spamming the console which is weird...