Jeg har et gammel eksempel liggende paa hylden (foer generics):
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 12345);
PrintWriter netpw = new PrintWriter(s.getOutputStream(), true);
BufferedReader netbr = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter conpw = new PrintWriter(System.out, true);
BufferedReader conbr = new BufferedReader(new InputStreamReader(System.in));
ServerHandler srv = new ServerHandler(conpw, netbr);
srv.start();
netpw.println("LOGIN " + args[0]);
String line;
System.out.print("Indtast text (afslut med CTRL/Z): ");
while((line = conbr.readLine()) != null) {
netpw.println("SEND " + line);
System.out.print("Indtast text (afslut med CTRL/Z): ");
}
netbr.close();
netpw.close();
s.close();
srv.interrupt();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerHandler extends Thread {
private BufferedReader br;
private PrintWriter pw;
public ServerHandler(PrintWriter pw, BufferedReader br) {
this.pw = pw;
this.br = br;
}
public void run() {
try {
String line;
while((line = br.readLine()) != null) {
pw.println(line);
}
} catch (IOException e) {
// nothing
}
}
}
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String[] args) {
try {
List lst = new ArrayList();
ServerSocket ss = new ServerSocket(12345);
while(true) {
Socket s = ss.accept();
ClientHandler cli = new ClientHandler(s, lst);
cli.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientHandler extends Thread {
private Socket s;
private BufferedReader br;
private PrintWriter pw;
private List lst;
private String user;
public ClientHandler(Socket s, List lst) {
try {
this.s = s;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
this.lst = lst;
user = "not logged in";
lst.add(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String line;
while((line = br.readLine()) != null) {
if(line.substring(0,6).equals("LOGIN ")) {
user = line.substring(6);
System.out.println(user + " login");
} else if(line.substring(0,5).equals("SEND ")) {
String msg = line.substring(5);
for(int i = 0; i < lst.size(); i++) {
ClientHandler cli = (ClientHandler)lst.get(i);
if(cli != this) {
cli.send(msg);
System.out.println(msg + " send to " + cli.user);
}
}
} else {
System.out.println("Unknown command : " + line);
}
}
} catch (IOException e) {
// nothing
} finally {
lst.remove(this);
}
}
public void send(String msg) {
pw.println(msg);
}
}