[Java]我写的Java聊天室程序(ChatRoom)

支持多用户聊天,客户端UDP发送消息到服务器,服务器TCP发送消息到每一个客户。

// Server [服务器]:

// Usage:  javac Server.java ;  java Server 7777

// Write by Hifan for C/S; Date: May 17 /2005 to May 30 /2005

import java.io.*;
import java.net.*;
import java.util.Vector;
import javax.swing.*;
import java.awt.event.*;

public class Server extends JFrame
{
 static ServerSocket serverSocket = null;
 static int      serverUDPport = 9999;
 static Vector vecSocket = new Vector(10,10);

 public static void main(String args[]) throws IOException
 {
  if(args.length!=1)
  {
   System.out.println("Usage:/njava Server [ServerPort]/nLike: java Server 7777/n");
   System.exit(-1);
  }
  
  // Create Server Socket!
  try{
   serverSocket=new ServerSocket(Integer.parseInt(args[0]));
   System.out.println("Successfully Listen on port: "+Integer.parseInt(args[0]));
  } catch (IOException e) {
   System.out.println("Could not Listen on port: "+Integer.parseInt(args[0]));
   System.exit(-1);
  }
  
  new JabberThread(9999).start();
  
   Frame
  Server myServer = new Server("Server - Listening at "+args[0]);
  myServer.addWindowListener(new WindowAdapter()
    {
     public void windowClosing(WindowEvent e)
     {   // QUIT□SERVER/n
      // Send "QUIT: SERVER/n" to LocalHost
      DatagramSocket socketUDP = null;
      String quit  = new String("QUIT: SERVER/n");
      byte[] buf   = new byte[256];
      buf = quit.getBytes();
      
      try {
       socketUDP = new DatagramSocket();
      } catch (SocketException e2) {
       System.err.println("SocketException: "+e2);
       System.out.println("Can not create UDP socket[to send QUIT: SERVER to LocalHost]!");
      }
      
      InetAddress address = null;
      try {
       address = InetAddress.getByName("LocalHost");
      } catch (UnknownHostException e2) {
       System.err.println("UnknownHostException: "+e2);
       System.out.println("Can not parse ServerIP[LocalHost]!");
      }
      DatagramPacket packet = new DatagramPacket(buf,buf.length,address,serverUDPport);
      try {
       socketUDP.send(packet);
      } catch (IOException e3) {
       System.err.println("IOException: "+e3);
       System.out.println("Can not send /"QUIT: SERVER//n/" throught UDP!");
      }
      
      System.exit(0);
     }
    });
  myServer.setSize(300,300);
  myServer.setVisible(true);
  
  
  boolean listening=true;
  while(listening)
  {
   System.out.println("Waitinging!");
   Socket socket = serverSocket.accept();
   BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   PrintWriter    os = new PrintWriter(socket.getOutputStream());
   
   // "HELO□<screen_name>/n"
   String read        = is.readLine();
   String screen_name = read.substring(5);
   
   // "WELCOME□<udp_port>/n"
   os.println("WELCOME "+serverUDPport);
   os.flush();
   
   // is.close();
   // os.close();
   
   vecSocket.addElement(screen_name);
   vecSocket.addElement(socket);
   
   System.out.println(screen_name+" connect successfully!");
  }
  serverSocket.close();
 }
 
 public Server(String str) { super(str); }
};

class JabberThread extends Thread
{
 DatagramSocket socketUDP;
 public JabberThread(int port)
 {
  try {
   socketUDP = new DatagramSocket(port);
  } catch (SocketException e) {
   System.err.println("SocketException: "+e);
   System.out.println("Can not create UDP server!");
  }
 }
 public void run()
 {
  boolean socketConnect = true;
  try {
   while(socketConnect)
   {
    // UDP to get message from Client!
    byte [] buf = new byte [256];
    DatagramPacket packet = new DatagramPacket(buf,buf.length);
    socketUDP.receive(packet);
    
    // Print the message on the Server Standard Output!
    String received = new String(packet.getData());
    for(int i=0;i<256;++i)  // "Hifan: I am Hifan!/n0000-256-0000"! trim can not!
    {
     char point = received.charAt(i);
     if( point == '/n') {
      received = received.substring(0,i+1);
      break;
     }
    }
    
    // If the message is QUIT message!
    String client_name = null;  // store the client name who send the message;
    boolean to_delete = false; // Flag show whether to delete the client[socket]
    if(received.substring(0,4).equals("QUIT"))
    {
     client_name = received.substring(6,received.length()-1);
     if(client_name.equals("SERVER"))
      socketConnect = false; // show whether to quit the server
     else
     {
      to_delete   = true;
      received    = client_name + ": QUIT/n";
     }
    }
    System.out.print(received);
    
    // Send the message to all Clients!
    for(int i=0;i<Server.vecSocket.size();i+=2)
    {
     String screen_name  = (String) Server.vecSocket.elementAt(i);
     Socket socket       = (Socket) Server.vecSocket.elementAt(i+1);
     
     PrintWriter os = new PrintWriter(socket.getOutputStream());
     os.print(received);
     os.flush();
    }
    
    // to delete the client;
    if(to_delete)
    {
     int index = 0 ;
     while( (index=Server.vecSocket.indexOf(client_name)) != -1 )
     {
      Server.vecSocket.remove(index);
      Server.vecSocket.remove(index);//not index+1,delete one so the size decrease 1;
      System.out.println(client_name + " has gone!");
     }
    }
    // to quit the Server
   }
  }
  catch (IOException e) {
   System.err.println("IOException: "+e);
   System.out.println("JabberThread error!");
  }
 }
}

// Client [客户端]

// run.bat: javac Client.java; java Client HiFan  LocalHost 7777

//Write by Hifan for Java Program. Date: May 17 /2005 to May 30 /2005

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;

public class Client implements ActionListener
{
 // Four Members
 JFrame  f;
 JButton  b;
 JTextField tf;
 static JTextArea ta;
 
 static JScrollPane s;

 
 static String screen_name;
 static String ServerIP;
 static int  ServerPort;
 static int  ServerPortUDP;

 
 static Socket   socket;
 static DatagramSocket socketUDP;

 String message;
 static String  serverMessage;

 static BufferedReader is;
 static PrintWriter  os;

 static boolean socketConnect = true;
 
 // main function
 public static void main(String args[]) throws UnknownHostException, IOException
 {
  judgeStandardInput(args);
  createSocket();
  Client myClient = new Client();
  
  while(socketConnect)
  {
   getMessageTCP();
   displayMessage();
   judgeServerMessage();
  }
  destroySocket();
  System.exit(0);
 }
 
 // Client Construct
 public Client()
 {
  f = new JFrame("ChatRoom[Client] - "+screen_name+" Connect");
  b = new JButton("Quit");
  tf = new JTextField(256);
  ta = new JTextArea(0,0);
  
  s   = new JScrollPane(ta); // s.setViewportView((Component)ta);
  
  ta.setEditable(false);

  f.addWindowListener(new WindowAdapter()
    {
     public void windowClosing(WindowEvent e)
     {
      if(socketConnect)
       sendMessageUDP("QUIT: " + screen_name + "/n");
      System.exit(0);
     }
    });
  b.addActionListener(this); // When Button b[Quit] is pressed;
  tf.addActionListener(this); // When press "Enter" in the TextField;

  f.getContentPane().setLayout(new BorderLayout()); // Default
  f.getContentPane().add("North",tf);
  f.getContentPane().add("Center",s);
  f.getContentPane().add("South",b);

  f.setSize(300,300);
  f.setVisible(true);
 }
 
 // Judge how much standard input.
 public static void judgeStandardInput(String args[])
 {
  if(args.length==3)
  {
   if(args[0].equals("QUIT") || args[0].equals("SERVER"))
    System.out.println("You can not login with /"QUIT/" or /"SERVER/"");
   screen_name = args[0];
   ServerIP = args[1];
   ServerPort = Integer.parseInt(args[2]);
  }
  else
  { // Tell how to use it!
   System.out.print("Usage:/njava Client [youName] [ServerIP] [Port]/nLike: Java Client Hifan 127.0.0.1 7777/n");
   System.exit(-1);
  }
 }

 // Create Socket
 public static void createSocket()
 {
  try {
   System.out.println("Connecting!");
   socket  = new Socket(ServerIP,ServerPort);
   System.out.println("Successfully connect to "+ServerIP+" at port "+ServerPort);
  } catch (UnknownHostException e) {
   System.err.println("UnknownHostException: "+e);
   System.out.println("Could not connect to "+ServerIP+" at port "+ServerPort);
   System.exit(-1);
  } catch (IOException e) {
   System.err.println("IOException: "+e);
   System.out.println("Can not connect to "+ServerIP+" at port "+ServerPort);
  }
  
  try {
   is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
   os=new PrintWriter(socket.getOutputStream());
  } catch (IOException e) {
   System.out.println("IOException: "+e);
   System.out.println("Can not Create BufferedReader and PrintWriter!");
  }
  
  // [The Protocol 1] Send "HELO□<screen_name>/n"
  sendMessageTCP("HELO "+screen_name);
  
  // [The Protocol 2] Wait to get "WELCOME□<udp_port>/n"
  try {
   String read = is.readLine();
   read = read.substring(8);
   
   System.out.println("Get Server UDP port: "+read);
   
   ServerPortUDP = Integer.parseInt(read);
  } catch (IOException e) {
   System.err.println("IOException: "+e);
   System.out.println("Can not get Server UDP port!");
  }
  
  // Create UDP socket
  try {
   socketUDP = new DatagramSocket();
  } catch (SocketException e) {
   System.err.println("SocketException: "+e);
   System.out.println("Can not create UDP socket!");
   System.exit(-1);
  }
 }
 
 // Destroy Socket
 public static void destroySocket()
 {
  try {
   os.close();
   is.close();
   socket.close();
   socketUDP.close();
   socket = null;
   socketUDP = null;
  } catch (IOException e) {
   System.err.println("IOException: "+e);
   System.out.println("Can not destroy Socket!");
  }
 }
 
 // Using TCP to send message from Client to Server
 public static void sendMessageTCP(String str)
 {
  os.println(str);
  os.flush();
 }
 
 // Using UDP to send message from Client to Server
 public void sendMessageUDP()
 {
  message = tf.getText();
  if(message.equals(""))
   return;
  message = screen_name + ": " + message + "/n";
  byte[] buf = new byte[256];
  buf = message.getBytes();

  InetAddress address = null;
  try {
   address = InetAddress.getByName(ServerIP);
  } catch (UnknownHostException e) {
   System.err.println("UnknownHostException: "+e);
   System.out.println("Can not parse ServerIP[" + ServerIP + "]!");
  }
  DatagramPacket packet = new DatagramPacket(buf,buf.length,address,ServerPortUDP);
  try {
   socketUDP.send(packet);
  } catch (IOException e) {
   System.err.println("IOException: "+e);
   System.out.println("Can not send message throught UDP!");
  }
  tf.setText("");
 }
 
 // Using UDP to send message from Client to Server
 public void sendMessageUDP(String message)
 {
  byte[] buf = new byte[256];
  buf = message.getBytes();

  InetAddress address = null;
  try {
   address = InetAddress.getByName(ServerIP);
  } catch (UnknownHostException e) {
   System.err.println("UnknownHostException: "+e);
   System.out.println("Can not parse ServerIP[" + ServerIP + "]!");
  }
  DatagramPacket packet = new DatagramPacket(buf,buf.length,address,ServerPortUDP);
  try {
   socketUDP.send(packet);
  } catch (IOException e) {
   System.err.println("IOException: "+e);
   System.out.println("Can not send message throught UDP!");
  }
 }
 
 // Get Message from Server Using TCP
 public static void getMessageTCP()
 {
  try {
   serverMessage = is.readLine();
  } catch (IOException e) {
   System.err.println("IOException: "+e);
   System.out.println("Can not get message throught TCP!");
  }
 }
 
 // display message got from server by TCP
 public static void displayMessage()
 {
  ta.append(serverMessage+"/n");
  System.out.println(serverMessage);
  // Set Position of ScrollBar!! Set View port is (0,max)
  Point p = new Point(0,60000); // Point(0,20*ta.getLineCount());
  s.getViewport().setViewPosition(p);
 }
 
 // to judge "quit" or "Server quit"
 public static void judgeServerMessage()
 {
  if(serverMessage.equals(screen_name+": QUIT"))
   socketConnect = false;
  if(serverMessage.equals("QUIT: SERVER"))
  {
   JOptionPane.showMessageDialog(null,"Sorry, Server is closed!","Server Quit",JOptionPane.WARNING_MESSAGE|JOptionPane.OK_OPTION);
   socketConnect=false;
  }
 }
 
 // Action Performed
 public void actionPerformed(ActionEvent e)
 {
  if(e.getSource()==b)
  {
   if(socketConnect)
    sendMessageUDP("QUIT: " + screen_name + "/n");
   System.exit(0);
  }
  if(e.getSource()==tf)  // When Press "Enter" in the TextField
  {
   if(socketConnect)
    sendMessageUDP();
  }
 }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页