Total Pageviews

Thursday, June 28, 2012

Working Java Socket Server & Client

A while ago I found some code to create a Java socket server and client. It didn't work very well, so I heavily modified it to work. This client / server are for a simple multi user chat program, and can easily be used for the base of much larger and more complex programs ( MMO any one? ) For now, it's just a chat program that operates on local host ( you can change the string "127.0.0.1" if you have a dedicated server )
In the client side, type in "quit" to exit the client, or "kill" to stop the server.
Server Code:
 package Server;  
   
 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 import java.io.PrintWriter;  
 import java.net.ServerSocket;  
 import java.net.Socket;  
 import java.util.HashSet;  
   
 public class ChatServer {  
   
   private static final int PORT = 9001;  
   private static HashSet<String> names = new HashSet<String>();  
   private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();  
        
   public static void main(String[] args) throws Exception {  
     System.out.println("The chat server is running.");  
     ServerSocket listener = new ServerSocket(PORT);  
     try {  
       while (true) {  
         new Handler(listener.accept()).start();  
       }  
     } finally {  
       listener.close();  
     }}  
             
   private static class Handler extends Thread {  
     private String name;  
     private Socket socket;  
     private BufferedReader in;  
     private PrintWriter out;  
 c Handler(Socket socket) {  
       this.socket = socket;  
     }  
             
     public void run() {  
       try {  
         in = new BufferedReader(new InputStreamReader(  
           socket.getInputStream()));  
         out = new PrintWriter(socket.getOutputStream(), true);  
   
         while (true) {  
           out.println("SUBMITNAME");  
           name = in.readLine();  
           if (name == null) {  
             return;  
           }  
           synchronized (names) {  
             if (!names.contains(name)) {  
               names.add(name);  
               break;  
             }}}  
         out.println("NAMEACCEPTED");  
         writers.add(out);  
         while (true) {  
           String input = in.readLine();  
           if (input == null) {return; }  
   
           for (PrintWriter writer : writers) {  
             writer.println("MESSAGE " + name + ": " + input);  
             if (input.equalsIgnoreCase("KILL")){  
                  System.exit (0);  
             }}}  
       } catch (IOException e) {  
         System.out.println(e);  
       } finally {  
         if (name != null) {  
           names.remove(name);  
         }  
         if (out != null) {  
           writers.remove(out);  
         }  
         try {  
           socket.close();  
         } catch (IOException e) {  
         }}}}}  

Client Code:
 package Client;  
   
 import java.awt.event.ActionEvent;  
 import java.awt.event.ActionListener;  
 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 import java.io.PrintWriter;  
 import java.net.Socket;  
 import javax.swing.JFrame;  
 import javax.swing.JOptionPane;  
 import javax.swing.JScrollPane;  
 import javax.swing.JTextArea;  
 import javax.swing.JTextField;  
   
 public class ChatClient {  
   
   BufferedReader in;  
   PrintWriter out;  
   JFrame frame = new JFrame("Chat Client");  
   JTextField textField = new JTextField(40);  
   JTextArea messageArea = new JTextArea(8, 40);  
   
   public ChatClient() {  
     textField.setEditable(false);  
     messageArea.setEditable(false);  
     frame.getContentPane().add(textField, "North");  
     frame.getContentPane().add(new JScrollPane(messageArea), "Center");  
     frame.pack();  
     textField.addActionListener(new ActionListener() {  
    
       public void actionPerformed(ActionEvent e) {  
            if(textField.getText().equalsIgnoreCase("quit")){  
                 JOptionPane.showMessageDialog(null,"Shutting Down Client");  
                 out.println("REMOVE-");  
                 System.exit(0);  
            }  
            else{  
            out.println(textField.getText());  
         textField.setText("");  
       }}});  
                }  
   private String getServerAddress() {  
        return "127.0.0.1";  
   }  
   
   private String getName() {  
     return JOptionPane.showInputDialog(  
       frame,  
       "Choose a screen name:",  
       "Screen name selection",  
       JOptionPane.PLAIN_MESSAGE);  
   }  
   
   private void run() throws IOException {  
   
     String serverAddress = getServerAddress();  
     Socket socket = new Socket(serverAddress, 9001);  
     in = new BufferedReader(new InputStreamReader(  
       socket.getInputStream()));  
     out = new PrintWriter(socket.getOutputStream(), true);  
     while (true) {  
       String line = in.readLine();  
       if(line.contains(":")){  
            String[] ss = line.split(":");  
   
            if(ss[1].equalsIgnoreCase(" KILL")){  
                 JOptionPane.showMessageDialog(null,"Shuting Down");  
              System.exit (0);  
              }}  
       if (line.startsWith("SUBMITNAME")) {  
         out.println(getName());  
       } else if (line.startsWith("NAMEACCEPTED")) {  
         textField.setEditable(true);  
       } else if (line.startsWith("MESSAGE")) {  
         messageArea.append(line.substring(8) + "\n");  
       }}}  
   public static void main(String[] args) throws Exception {  
     ChatClient client = new ChatClient();  
     client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
     client.frame.setVisible(true);  
     client.run();  
   }}  
   

No comments:

Post a Comment