Chat serveur
Client
import java.net.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
public class Client {
BufferedReader in;
PrintWriter out;
Socket socket;
String name;
Gui g;
Client(JFrame f){
init();
g = new Gui(f);
}
class Gui{
JTextArea serv;
JTextField cl;
Gui (JFrame f){
f.setLayout(new BorderLayout());
serv = new JTextArea(20,10);
serv.setEditable(false);
serv.setBackground(new Color(230,230,230));
serv.setFont(new Font("SANS_SERIF", Font.BOLD, 14));
cl = new JTextField(30);
f.add("Center",new JScrollPane(serv));
f.add("South",cl);
cl.addActionListener(new SrvL());
(new Rcv()).start();
}
class SrvL implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
String st=cl.getText();
send(st);
cl.setText("");
}
catch (Exception ex){
System.out.println("exception: "+ex);
System.out.println("closing...");
try{
socket.close();
}
catch (Exception expt){
System.out.println(expt);
}
}
}
}
class Rcv extends Thread{
public void run(){
for(;;){
try {
sleep(400);
} catch (InterruptedException e){}
try{
serv.append(in.readLine()+"\n");
serv.setCaretPosition(serv.getDocument().getLength());
} catch (IOException e1){break;}
}
System.out.println(" closing reading thread...");
try{
socket.close();
}
catch (Exception expt){
System.out.println(expt);
}
System.exit(0);
}
}
}
public void init(){
try{
do{
name = JOptionPane.showInputDialog("Please enter your name");
} while((name == null)|| (name.length()==0));
String server = null;
InetAddress addr = InetAddress.getByName(server);
System.out.println("addr = " + addr);
socket = new Socket(addr, ChatSrv.PORT);
System.out.println("socket = " + socket);
//BufferedReader sin = new BufferedReader(
// new InputStreamReader(System.in));
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
// Output is automatically flushed
// by PrintWriter:
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
out.println(name); // sending client's name to the server
}catch (Exception e){
System.out.println("exception: "+e);
System.out.println("closing...");
try{
socket.close();
}catch (Exception e2){
System.out.println("no server running");
System.exit(5);
}
}
}
void send(String s){
if(s.length()==0){
int quit = JOptionPane.showConfirmDialog(null, "Exit chat");
if(quit == 0) {
out.println("END");
System.out.println("closing...");
try{
socket.close();
}
catch (Exception expt){
System.out.println(expt);
}
System.exit(0);
}
}
else out.println(name+": "+s);
}
public static void main(String[] args )throws IOException{
JFrame frame =new JFrame();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Client cl = new Client(frame);
frame.setTitle(cl.name + " (empty line to exit)");
frame.setSize(500,300);
frame.setVisible(true);
}
}Chat serveur - réalisation par ArrayList
import java.io.*;
import java.net.*;
import java.util.*;
class Clint{
String name;
PrintWriter pw;
Clint(String name, PrintWriter p){
this.name = name;
this.pw =p;
}
}
class Clients{
private ArrayList<Clint> cl;
public Clients(){
cl = new ArrayList<Clint>(10);
}
public synchronized void addC(Clint c){
cl.add(c);
}
public synchronized void rmvC(Clint c){
cl.remove(c);
}
public synchronized void sendC(String s){
Iterator<Clint> itr = cl.iterator();
while(itr.hasNext()) {
PrintWriter p=(PrintWriter)(itr.next().pw);
p.println(s);
}
}
public synchronized int nCl(){
return cl.size();
}
}
//...............................................................
class ServeOneClient extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private Clint cl;
Clients clt;
public ServeOneClient(Socket s,Clients clt) throws IOException {
socket = s;
this.clt =clt;
in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Enable auto-flush:
out = new PrintWriter( new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
),
true);
// If any of the above calls throw an
// exception, the caller is responsible for
// closing the socket. Otherwise the thread
// will close it.
String name = in.readLine(); // reading the client name
clt.addC(cl=new Clint(name,out));
start(); // Calls run()
}
public void run() {
System.out.println("join a new client "+ cl.name+ " - total number "+ clt.nCl());
clt.sendC(" join a new client "+ cl.name + ". Total number clients "+clt.nCl()); //informing the clients for new participant
try {
while (true) {
String str = in.readLine();
if (str.equals("END")) break;
System.out.println(str);
clt.sendC(str);
}
} catch (IOException e) { }
finally {
try {
clt.rmvC(cl);
System.out.println("disconect client "+cl.name + ". Total number "+clt.nCl());
clt.sendC("disconecting client "+ cl.name + ". Total number clients connected "+clt.nCl());
socket.close();
} catch(IOException e) {}
}
}
}
//................................................................................
public class ChatSrv {
static final int PORT = 9090;
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Server Started");
Clients clt = new Clients();
try {
while(true) {
// Blocks until a connection occurs:
Socket socket = s.accept();
try {
new ServeOneClient(socket,clt);
} catch(IOException e) {
// If it fails, close the socket,
// otherwise the thread will close it:
socket.close();
}
}
} finally {
s.close();
}
}
}