Here is the code for the Server.

001package chatappserver;
002 
003import java.net.*;
004import java.io.*;
005import java.util.Vector;
006import java.lang.*;
007 
008public class ChatappServer {
009     
010    private static int port = 1234;
011    private static ServerSocket server = null;
012    private static Socket clientSocket;
013    private static String line;
014    private static BufferedReader streamIn;
015    private static PrintStream streamOut;
016     
017     
018    private static Vector<String> usernames = new Vector<String>();
019    private static Vector<PrintStream> streams = new Vector<PrintStream>();
020     
021    public static void main(String[] args) throws IOException{
022         
023        try{
024            System.out.println("Connecting to port " + port + " ....");
025            server = new ServerSocket(port);
026            System.out.println("Chat application server is now running..");
027            while(true){
028            clientSocket = server.accept();
029            chatHandler c = new chatHandler(clientSocket);
030            c.start();
031            }
032        }
033        catch(IOException e){
034            System.out.println("Couldn't connect to the port!");
035        }
036        finally{
037            server.close();
038        }      
039    }
040     
041    private static class chatHandler extends Thread{
042         
043        private Socket clientSocket;
044         
045        public chatHandler(Socket clientSocket){           
046            super("chatHandler");
047            this.clientSocket = clientSocket;
048        }
049         
050        public void run(){
051            
052            try{
053              streamIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
054              streamOut = new PrintStream(clientSocket.getOutputStream(), true);
055             
056              while(true){
057                streamOut.println("Username");
058                String line = streamIn.readLine();
059                if (line == null){
060                    return;           
061                }
062                try{
063                    synchronized(usernames){
064                        if(!usernames.contains(line)){
065                            usernames.add(line);
066                            break;
067                        }
068                    }
069                }
070                catch(Exception e){
071                    System.out.println(e);
072                }               
073              }
074              streamOut.println("Welcome");
075              streams.add(streamOut);
076               
077              while(true){
078              String message = streamIn.readLine();
079              if(message == null){
080                  return;
081              }
082              for(PrintStream stream : streams){
083                  stream.println("From " + line + ": " + message);
084              }
085               
086            }
087            }
088            catch(IOException e){
089                System.out.println(e);
090                 
091            }
092            finally{
093                if(line != null && streamOut != null){
094                    usernames.remove(line);
095                    streams.remove(streamOut);
096                }
097                try{
098                    clientSocket.close();
099                }
100                catch(IOException e){
101                    System.out.println(e);
102                }
103                 
104            }
105             
106                 
107            }
108             
109             
110        }
111         
112    }




The Client code is here..

01package chatappclient;
02 
03import java.net.*;
04import java.io.*;
05import javax.swing.JFrame;
06import javax.swing.JTextArea;
07import javax.swing.JTextField;
08import javax.swing.JButton;
09import javax.swing.*;
10import java.awt.event.*;
11 
12public class ChatappClient {
13     
14    private static int port = 1234;
15    JFrame window = new JFrame("Chat");
16    JButton sendBox = new JButton("Send");
17    JTextField inputMsg = new JTextField(35);
18    JTextArea outputMsg = new JTextArea(1035);
19    private static BufferedReader streamIn;
20    private static PrintStream streamOut;
21     
22    public static void main(String[] args) throws Exception{
23        ChatappClient client = new ChatappClient();
24        client.window.setVisible(true);
25        client.window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
26        client.run();       
27    }
28     
29    public ChatappClient(){
30         
31        inputMsg.setSize(4020);
32        sendBox.setSize(510);
33        outputMsg.setSize(3550);
34        inputMsg.setEditable(false);
35        outputMsg.setEditable(false);
36        window.getContentPane().add(inputMsg, "South");
37        window.getContentPane().add(outputMsg, "East");
38        window.getContentPane().add(sendBox, "West");
39        window.pack();
40        sendBox.addActionListener(new ActionListener(){
41            public void actionPerformed(ActionEvent e){
42                streamOut.println(inputMsg.getText());
43                inputMsg.setText("");
44            }
45        });
46        inputMsg.addActionListener(new ActionListener(){
47            public void actionPerformed(ActionEvent e){
48                streamOut.println(inputMsg.getText());
49                inputMsg.setText("");
50            }
51        });          
52    }
53     
54    private String getUsername(){
55        return JOptionPane.showInternalInputDialog(window, "Server IP Address:""Welcome to Chat", JOptionPane.QUESTION_MESSAGE);
56    }
57     
58    private void run() throws IOException{
59        Socket clientSocket = new Socket("localhost", port);
60        streamIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
61        streamOut = new PrintStream(clientSocket.getOutputStream(), true);
62     
63        while(true){
64            String line = streamIn.readLine();
65            if(line.startsWith("Username")){
66                streamOut.println(getUsername());
67            }else if(line.startsWith("Welcome")){
68                inputMsg.setEditable(true);
69            }else if(line.startsWith("From")){
70                outputMsg.append(line.substring(10)+ "\n");
71            }
72        }  
73    }
74}


출저 : http://www.dreamincode.net/forums/topic/277518-chat-using-socketssingle-server-with-multiple-clients/

+ Recent posts