基于Socket简单的聊天程序

来源:互联网 发布:免费邮箱服务器软件 编辑:程序博客网 时间:2024/04/27 14:14

昨天CSDN一个哥们,说让写个聊天的小程序,主要昨晚太晚了,今天早晨起来上班,第一件事,就是写写这个小程序,和同事两个人,实验了下,还是满有意思的。

 

一下是客户端的Applet代码:

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Event;
import java.awt.TextArea;
import java.awt.TextField;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
/**
 * @author closewubq 客户端
 */
public class ClientApplet extends Applet implements Runnable {
 private static final long serialVersionUID = 1L;
 private TextArea textArea;
 private TextField textfield;
 private DataInputStream in;
 private DataOutputStream out;

 public void init() {
  this.setLayout(null);
  this.setSize(426, 266);
  this.textArea = new TextArea(10, 10);
  this.textfield = new TextField();
  in = null;
  out = null;
  try {
   URL url = this.getCodeBase();
   InetAddress inetAddress = InetAddress.getByName(url.getHost());
   Socket socket;
   socket = new Socket(inetAddress, 5555);
   in = new DataInputStream(socket.getInputStream());
   out = new DataOutputStream(socket.getOutputStream());
  } catch (Exception e) {
   System.out.println("Error:" + e);
  }
  this.setLayout(new BorderLayout());
  this.add("Center", textArea);
  this.add("South", this.textfield);
  this.textArea.setEditable(false);
  new Thread(this).start();
 }

 public boolean handleEvent(Event event) {
  String str = this.textfield.getText();
  if (event.target == this.textfield && (event.id == Event.ACTION_EVENT)) {
   this.textfield.setText("");
   try {
    out.writeUTF(str);
   } catch (IOException e) {
    System.out.println(e.getMessage());
   }
   return true;
  } else {
   return super.handleEvent(event);
  }
 }

 @Override
 public void run() {
  try {
   while (true) {
    String s = in.readUTF();
    this.textArea.append(s + "/n");
   }
  } catch (Exception e) {
   this.textArea.append("Network problem or server down./n");
   this.textfield.setVisible(false);
  }
 }

 public void stop() {
  try {
   out.writeUTF("leave");
  } catch (IOException e) {
   System.out.println(e.getMessage());
  }
 }
}

 

服务器端:

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
/**
 *
 * @author closewubq
 * 聊天程序 服务器端
 */
public class ChatServer {
 public static void main(String[] args) {
  ServerSocket socket = null;
  Vector<ServerThread> threads = new Vector<ServerThread>();
  System.out.println("Now listen....");
  try {
   socket = new ServerSocket(5555);
  } catch (Exception e) {
   System.out.println("new ServerSocket is fialed");
   return;
  }
  try {
   int nid = 0;
   while (true) {
    Socket s = socket.accept();
    System.out.println("accepted");
    ServerThread st = new ServerThread(s, threads);
    st.setID(nid++);
    threads.addElement(st);
    new Thread(st).start();
    for (int i = 0; i < threads.size(); i++) {
     ServerThread st1 = threads.elementAt(i);
     st1.write("<#>welcome" + st.getID() + "to enter chartRoom");
    }
    System.out.println("Lienten again");
   }
  } catch (Exception e) {
   System.out.println("Server shut down");

  }
 }
}

 

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Vector;
/**
 * @author closewubq
 * 接受所有客户连接的socket
 */
public class ServerThread implements Runnable{
 Vector<ServerThread> threads;
 Socket socket=null;
 DataInputStream in=null;
 DataOutputStream out=null;
 int nid;
 String name;
 public ServerThread(Socket s,Vector<ServerThread> threads){
  socket=s;
  this.threads=threads;
  try{
   in=new DataInputStream(socket.getInputStream());
   out=new DataOutputStream(socket.getOutputStream());
   
  }catch(Exception e){
   
  }
  
 }
 public void run(){
  System.out.println("thread is running");
  try{
   while(true){
    String s=in.readUTF();
    if(s==null){
     break;
    }
    if(s.trim().equals("leave")){
     for(int i=0;i<this.threads.size();i++){
      ServerThread st=this.threads.elementAt(i);
      st.write("**"+this.getID()+"leave..."+"***");
     }
    }
    else{
     for(int i=0;i<this.threads.size();i++){
      ServerThread st=this.threads.elementAt(i);
      st.write("<"+this.getID()+">Say:"+s);
     }
    }
   }
  }catch(Exception e){
   e.printStackTrace();
  }
  this.threads.removeElement(this);
  try{
   socket.close();
  }catch(Exception e){
   
  }
 }
 
 public void write(String msg){
  synchronized(out){
   try{
    out.writeUTF(msg);
   }catch(IOException e){
    
   }
  }
 }
 public void setID(int nid){
  this.nid=nid;
 }
 
 public int getID(){
  return this.nid;
 }
}

 

如果你想验证多人聊天,你需要将客户端的程序分发给大家,并且将

InetAddress inetAddress = InetAddress.getByName(url.getHost());

中url.getHost()修改成服务器端的IP,比如服务器端IP为192.168.1.1的话。那么就成为:

InetAddress inetAddress = InetAddress.getByName("192.168.1.1");

如果在Eclipse中执行的话,首先执行服务器端代码,然后在执行客户端代码。接着就可以群聊了。忽忽!

 

原创粉丝点击