找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1338|回复: 8

我写的一个网络聊天室代码(JAVA)

[复制链接]
发表于 2008-8-13 23:30:29 | 显示全部楼层 |阅读模式
QUOTE:

老师的作业,还有很多地方要改进,主要是SOCKET和线程编程

后来改了一个用线程池的版本,忘了丢哪了.......

等学了数据库,就开发个类似qq的聊天程序...快了..

代码很乱,我也没写注释...看着可能很不爽....

[此帖子已经被作者于[lastedittime]1218641715[/lastedittime]编辑过]
 楼主| 发表于 2008-8-13 23:32:33 | 显示全部楼层
QUOTE:

TestServer.java

代码

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.TimeZone;
import java.io.*;

 

public class TestServer extends Thread {
 ServerSocket ss = null;
 private static TestServer instance;
 LinkedList<rintStream> speaker;

 LinkedList<Thread> tt;

 boolean accept;
 public static  TestServer getInstance(){
  if(instance==null)instance= new TestServer();
  return instance;
 }
 private TestServer() {
  accept = true;
  speaker = new LinkedList<rintStream>();
  tt = new LinkedList<Thread>();
  try {
   //ss = new ServerSocket(80);
   ss = new ServerSocket(7456);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public void run() {
  if (ss != null) {
   while (accept) {
    try {
     Socket so = ss.accept();// 如果客户不连接会停在这里
     System.out.println("somebody connected~!");
     Thread t = new Thread(new Handler(so, speaker));
     tt.add(t);
     t.start();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
 }

 public void close() {
  try {
   accept = false;
   if (speaker != null) {
    for (PrintStream ps : speaker) {
     if (ps != null) {
      ps.println("bye");
      ps.close();
     }
    }
   }
   if (tt != null) {
    for (Thread ps : tt) {
     if (ps != null)
      ps.interrupt();
    }
   }
   if (ss != null)
    ss.close();
   System.exit(0);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 public static void main(String[] args) throws Exception {
  TestServer s = TestServer.getInstance();
  s.start();
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String tmp = "";
  while ((tmp = br.readLine()) != null) {
   if (tmp.equalsIgnoreCase("bye"))
    s.close();
   for (PrintStream ps : s.speaker) {
    if (ps != null) {
     ps.println(tmp);
    }
   }
  }
 }
}

class Handler implements Runnable {
 private Socket socket = null;

 LinkedList<rintStream> speaker;

 Handler(Socket s, LinkedList<rintStream> speaker) {
  this.socket = s;
  this.speaker = speaker;
 }

 public void run() {
  try {
   InputStream is = socket.getInputStream();
   OutputStream os = socket.getOutputStream();
   BufferedReader br = new BufferedReader(new InputStreamReader(is));
   rintStream ps = new PrintStream(os);
   String temp = null;
   speaker.add(ps);

   SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
   for (PrintStream p : speaker)
    p.println("[" + socket.getInetAddress().getHostAddress() +"|"+sdf.format(GregorianCalendar.getInstance().getTime())+ "]"+"来了");
   while ((temp = br.readLine()) != null) {
    if (temp.equalsIgnoreCase("bye")) {
     speaker.remove(ps);
     for (PrintStream p : speaker)
      p.println("[" + socket.getInetAddress().getHostAddress() +"|"+sdf.format(GregorianCalendar.getInstance().getTime())+ "]"+ "跑了");
     break;
    }
    temp = "[" + socket.getInetAddress().getHostAddress() +"|"+sdf.format(GregorianCalendar.getInstance().getTime())+ "]" + temp;
    for (PrintStream p : speaker)
     p.println(temp);
    //system.out.println(temp);
   }
   System.out.println("somebody leaved~!");
   ps.close();
   br.close();
   os.close();
   is.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

回复

使用道具 举报

 楼主| 发表于 2008-8-13 23:33:53 | 显示全部楼层
QUOTE:
ChatForm.java

 


import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatForm extends JFrame implements KeyListener, WindowListener {
 private static final long serialVersionUID = 1L;

 private JTextArea content;

 private JTextField word;

 private JTextField name;
 private Alert al;

 Socket so;

 rintStream ps;

 BufferedReader br;

 ChatForm() throws Exception {
  content = new JTextArea("", 20, 40);
  // 不可编辑
  content.setEnabled(false);
  // 可滚动
  JScrollPane jsp = new JScrollPane(content);

  word = new JTextField("", 40);
  // 添加事件
  word.addKeyListener(this);
  name = new JTextField("", 10);
  name.setEnabled(false);
  word.setEnabled(false);
  JPanel jp = new JPanel();
  this.setTitle("简单聊天室");
  jp.add(name);
  jp.add(word);
  this.addWindowListener(this);
  this.setLayout(new BorderLayout());
  this.add(jsp, BorderLayout.CENTER);
  this.add(jp, BorderLayout.SOUTH);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.pack();
  this.setVisible(true);
  startClient();
 }
 public void setUserName(String name){
  this.name.setText(name);
 }
 public void startClient() throws Exception {
  int i = 0;
  while (so == null) {
   i++;
   try {
    so = new Socket("192.168.0.123", 7456);
    al = new Alert(this,"",false);
    al.setMessage("请输入您的名字:");
    name.setEnabled(true);
    word.setEnabled(true);
   } catch (Exception e) {
    if(i>10){System.out.println("服务器还是没有开启,可能不会开了,我走了.");Thread.sleep(2000);System.exit(0);}
    content.setText("服务器未开启,程序10秒钟后重新连接,第"+i+"次尝试\r\n");
    Thread.sleep(10000);
    // System.exit(0);
   }
  }
  content.setText("连接到服务器咯\r\n别忘了给自己起个名字");
  InputStream is = so.getInputStream();
  OutputStream os = so.getOutputStream();
  br = new BufferedReader(new InputStreamReader(is));
  ps = new PrintStream(os);
  Thread t = new Thread() {
   public void run() {
    String tmp = null;
    try {
     while ((tmp = br.readLine()) != null) {
      if(tmp.equalsIgnoreCase("bye")){
       content.setText( "服务器退了,我们也退咯"+"\r\n" +content.getText() );
       Thread.sleep(1000);
       close();
       
      }
      content.setText( tmp+"\r\n" +content.getText() );
     }
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  };
  t.start();
 }

 public static void main(String[] args) throws Exception {
  new ChatForm();
 }

 public void keyPressed(KeyEvent e) {
 }

 public void close() {
  if(ps!=null)ps.println("bye");
  try {
   if(br!=null)br.close();
   if(ps!=null)ps.close();
   if(so!=null)so.close();
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e1) {
    e1.printStackTrace();
   }
   System.exit(0);
  } catch (IOException e1) {
   e1.printStackTrace();
  }
 }

 public void sendMsg(String s) throws Exception {
  ps.println(s);
 }

 public void keyReleased(KeyEvent e) {
  int tmp = e.getKeyCode();
  if (KeyEvent.VK_ENTER == tmp) {
   String s = word.getText();
   String sname = name.getText();
   if (!s.equalsIgnoreCase("")) {
    if (s.equalsIgnoreCase("bye")) {
     close();
    }
    String stmp = sname + ":" + s;

    try {
     sendMsg(stmp);
    } catch (Exception e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
    }
    // content.setText(content.getText() + stmp+"\r\n");
    word.setText("");
   }
  }
 }

 public void keyTyped(KeyEvent e) {
 }

 public void windowActivated(WindowEvent e) {
 }

 public void windowClosed(WindowEvent e) {
 }

 public void windowClosing(WindowEvent e) {
  close();
 }

 public void windowDeactivated(WindowEvent e) {
 }

 public void windowDeiconified(WindowEvent e) {
 }

 public void windowIconified(WindowEvent e) {
 }

 public void windowOpened(WindowEvent e) {
 }

}

回复

使用道具 举报

 楼主| 发表于 2008-8-13 23:34:30 | 显示全部楼层
QUOTE:
Alert.java

import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Alert extends JDialog implements ActionListener {
 private JLabel messageLable;
 private JButton affirm;
 private JTextField name;
 private ChatForm f;
 Alert(ChatForm owner, String title, boolean modal){
  super(owner,title,modal);
  f=owner;
  init();
 }

 public void setMessage(String message){
  messageLable.setText(message);
  this.pack();
  this.setVisible(true);
 }
 public void setAffirmLisener(){
  
 }
 public void init(){
  messageLable = new JLabel("请输入您的名字:");
  name = new JTextField("", 10);
  affirm = new JButton("确定");
  affirm.addActionListener(this);
  this.setLayout(new BorderLayout());
  this.add(messageLable, BorderLayout.NORTH);
  this.add(name, BorderLayout.NORTH);
  this.add(affirm, BorderLayout.SOUTH);
  this.setVisible(false);
  this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
  this.pack();
 }

 public void actionPerformed(ActionEvent e) {
  String com = e.getActionCommand();
  if("确定".equalsIgnoreCase(com)){
   f.setUserName(name.getText());
   this.setVisible(false);
  }
  
 }
}

回复

使用道具 举报

发表于 2008-8-15 09:04:41 | 显示全部楼层
看不懂了,帮顶!
回复

使用道具 举报

发表于 2008-8-15 12:37:29 | 显示全部楼层
人才&nbsp; 顶一个
回复

使用道具 举报

发表于 2008-10-31 09:11:22 | 显示全部楼层

这个聊天室的代码我也写过的。也是老师布置的作业。。

http://jinanqikan.uu1001.com/(我的个人论坛)

欢迎到我的论坛分享你的电脑知识!

济南期刊采编中心站(www.7kan.org.cn)(天之信公司采编部)

国内广告业务——提供学术理论性期刊发表咨询服务

职称论文  中级职称   高级职称   科研项目

保证发正规刊物,非增刊,非假刊。优质服务。评定职称。

刊物级别:普刊(省级、国家级);核心刊物

刊物类别:教学教育、经济管理、科技工程、医疗医药、文学艺术等

具体合作期刊,请登陆www.7kan.org.cn查询。

 

客户群:以济南为中心的全国范围。

 

服务保障:凡是成功与我们合作的,一概提供有公司正规盖章证明文件及收据一份(用途:

如发现错发、漏发、发假刊等现象,可以凭此进行补偿,或向有关部门投诉。

注:公章拥有法律效应)

 

济南天之信公司 

济南经十西路27号恒生大厦3G  天之信公司 采编部

投稿热线:0531-87180050  89184800

投稿信箱:7kan@vip.163.com

在线QQ   1062442675                联系人:郭

(如有工作繁忙的朋友,我们提供免费修改服务,和有偿代写服务,具体情况请联系我们)

 

特注:高质量稿件,不急用的请投递qikan@vip.sohu.com信箱。要注明一下。

 

推荐:《中国高新技术企业》

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表