Hey guys, i would like to multi-thread a Socket connection in Java. So for example its a server which will accept more than one connection - at the moment i have: s = new ServerSocket(socket); for the socket. Any help would be great!
Printable View
Hey guys, i would like to multi-thread a Socket connection in Java. So for example its a server which will accept more than one connection - at the moment i have: s = new ServerSocket(socket); for the socket. Any help would be great!
Go through this useful link : Socket Communications
Hope that helps,
Goldest
try {
s = new ServerSocket(socket);
} catch (IOException e) { }
while (true) {
try {
s1 = s.accept();
os = s1.getOutputStream();
dos = new DataOutputStream (os);
try{
Thread.sleep(delay);
}
catch(InterruptedException e){}
dos.writeUTF(sendString);
dos.close();
os.close();
s1.close();
} catch (IOException e)
So this is what i have, how would i incorperate it?
A few remarks:
1) stick "[code]" before your program code and "[/code]" after it for readablility reasons.
2) why do you make your thread sleep for a while?
3) I don't see any attempt to use multiple Threads.
4) Incorporate that bit of code into what?
kind regards,
Jos
Yeah, basiclly i can input a delay for the server (to simulate latency). At the moment my server will only support one client at a time - thats why id like to be able to support multiple connections. Im new to Java so dont know how to incorprate it! Many thanks.
Simply create a connhandler class in your server class
The idea is to create a new instance starting at the socket connection
and just write this in the constructor:Code:private class connHandler implements Runnable{
private Socket client;
public connHandler(){
try {
System.out.println("Waiting.....");
client = server.accept();
System.out.println("Connection Established");
Thread t = new Thread(this);
t.start();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void run() {
// whatever code you want to run
}
Code:s = new ServerSocket(socket)
while(true){
connHandler handler = new connHandler();
}
Thanks for your reply. Im just confused as to where it would go. I have some variables above the code i pasted. and then the gui information. I have a few text boxes - one for the delay and one for the Socket Port. Would any of that need to change?
Would i put all my existing code inside where it says "run what ever code you want "?