Chat сървър
Клиент
import java.net.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
public class Client {
BufferedReader in;
PrintWriter out;
InetAddress addr;
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);
}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 сървър с ArrayList
import java.io.*;
import java.net.*;
import java.util.*;
class Clients{
private ArrayList<PrintWriter> pW;
public Clients(){
pW = new ArrayList<PrintWriter>(10);
}
public synchronized void addC(PrintWriter p){
pW.add(p);
}
public synchronized void rmvC(PrintWriter p){
pW.remove(p);
}
public synchronized void sendC(String s){
Iterator<PrintWriter> itr = pW.iterator();
while(itr.hasNext()) {
PrintWriter p=(PrintWriter)itr.next();
p.println(s);
}
}
public synchronized int nCl(){
return pW.size();
}
}
//...............................................................
class ServeOneClient extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
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.
clt.addC(out);
start(); // Calls run()
}
public void run() {
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(out);
System.out.println("disconect a client. Total number "+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);
System.out.println("join a new client - total number "+ clt.nCl());
} catch(IOException e) {
// If it fails, close the socket,
// otherwise the thread will close it:
socket.close();
}
}
} finally {
s.close();
}
}
}
Chat сървър с масив
import java.io.*;
import java.net.*;
class ClientsA{
private int size;
private PrintWriter pW[];
public ClientsA(){
pW = new PrintWriter[10];
size=0;
}
public synchronized void addC(PrintWriter p){
if(size==pW.length){
PrintWriter buf[]=new PrintWriter[pW.length*2];
System.arraycopy(pW,0,buf,0,pW.length);
pW=buf;
}
pW[size++]=p;
}
public synchronized void rmvC(PrintWriter p){
for(int i=0;i<pW.length;i++){
if(pW[i]==p){
pW[i]=pW[size--];
break;
}
}
}
public synchronized void sendC(String s){
for(int i=0;i<size;i++){
pW[i].println(s);
}
}
public synchronized int nCl(){
return size;
}
}
//.................................................................................................
class ServeOneClientA extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
ClientsA clt;
public ServeOneClientA(Socket s,ClientsA 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.
clt.addC(out);
start(); // Calls run()
}
public void run() {
try {
while (true) {
String str = in.readLine();
if (str.equals("END")) break;
System.out.println(str);
//out.println(str+" total:"+c.getC());
clt.sendC(str);
}
} catch (IOException e) { }
finally {
try {
clt.rmvC(out);
System.out.println("disconect a client. Total number "+clt.nCl());
socket.close();
} catch(IOException e) {}
}
}
}
//.....................................................................................................................
public class ChatSrvA {
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();
}
}
}