synchronized su awarenes e chat via tcp
This commit is contained in:
86
socket_chat_tcp/ServerClientHandler.java
Normal file
86
socket_chat_tcp/ServerClientHandler.java
Normal file
@@ -0,0 +1,86 @@
|
||||
package socket_chat_tcp;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.Socket;
|
||||
import java.util.Iterator;
|
||||
import java.util.Vector;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Created with xgiovio.macbookair.
|
||||
* User: xgiovio
|
||||
* Date: 02/12/14
|
||||
* Time: 17:36
|
||||
*/
|
||||
public class ServerClientHandler extends Thread {
|
||||
|
||||
|
||||
|
||||
public ServerClientHandler (Socket isclient){
|
||||
sclient=isclient;
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
synchronized (vs) {
|
||||
vs.add(sclient);
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
DataInputStream i = new DataInputStream(new BufferedInputStream(sclient.getInputStream()));
|
||||
name = i.readUTF();
|
||||
broadcast(name + " si e' connesso");
|
||||
while (true){
|
||||
String m = i.readUTF();
|
||||
broadcast(name + ": " + m);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
|
||||
}
|
||||
|
||||
finally {
|
||||
try {
|
||||
sclient.close();
|
||||
synchronized (vs){
|
||||
vs.remove(sclient);
|
||||
}
|
||||
broadcast(name + " si e' disonnesso");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void broadcast (String s){
|
||||
Iterator<Socket> it = vs.iterator();
|
||||
for (;it.hasNext();){
|
||||
Socket next = it.next();
|
||||
if (next != sclient) {
|
||||
try {
|
||||
DataOutputStream o = new DataOutputStream(new BufferedOutputStream(next.getOutputStream()));
|
||||
o.writeUTF(s);
|
||||
o.flush();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private String name;
|
||||
private final Socket sclient;
|
||||
private static final Vector<Socket> vs = new Vector<Socket>();
|
||||
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user