用java写的基于Socket的简单即时通讯程序

用java写的基于Socket的简单即时通讯程序,用户可以注册并登录,也可以作为游客身份使用.
/**//*
 *服务端
 */
package edu.jlu.fuliang;

import java.io.*;
import java.net.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class Server extends JFrame implements Runnable {
 private ServerSocket server;
 private Socket connection;
 private OutputStream output;
 private InputStream input;
 private Thread outThread;
 private JTextArea display;
 private JTextField text1;
 private JButton startButton;
 
 public static void main(String args[]) {
  Server s = new Server();
  s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }

 public Server() {
  super("Server");
  startButton = new JButton("Start the server");
  text1 = new JTextField(20);
  display = new JTextArea(7, 30);
  display.setEditable(false);
 Container container = getContentPane();
  container.setLayout(new BorderLayout());
  container.add(startButton,BorderLayout.NORTH);
  container.add(new JScrollPane(display),BorderLayout.CENTER);
  container.add(text1,BorderLayout.SOUTH); 

 /**//*
   * 给开始按钮添加监听器。
   */
  startButton.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e) {
    display.setText("启动服务器 ");
    startButton.setEnabled(false);
    try {
     //端口设为5000,最大连接请求为100个
     server = new ServerSocket(5000, 100);
     connection = server.accept();
     output = connection.getOutputStream();
     input = connection.getInputStream();
     output.write("连接成功! ".getBytes());
     outThread = new Thread(Server.this);
     outThread.start();
     } catch (IOException ee) {
    }
   }
  });
  
  /**//*
  /*给文本域添加键盘监听器,按回车发送信息。
        */
  
  text1.addKeyListener(new KeyAdapter(){
   public void keyPressed(KeyEvent ke) {
    if(ke.getKeyCode() == KeyEvent.VK_ENTER){
     byte writeBytes[] = new byte[50];
     String s = "Server: " + text1.getText() + "";
     text1.setText("");
     writeBytes = s.getBytes();
     display.append(s+" ");
     try {
      output.write(writeBytes);
     } catch (IOException ee) {
     }
     if (s.trim().equals("Server: exit")) {
      outThread.stop();
      quit();
     }
    }
   }
  });
  setSize(300, 400);
  setResizable(false);
  setVisible(true);
 }

 public void run() {
  while (true) {
   byte readBytes[] = new byte[50];
   try {
    input.read(readBytes);//读去对方发送的消息
   } catch (IOException e) {
   }
   String s = new String(readBytes);
   display.append(s+" ");
   if (s.trim().equals("Client: exit"))
    break;
  }
  quit();
 }

 public void quit() {
  try {
   output.close();
   input.close();
   connection.close();
  } catch (IOException e) {
  }
  startButton.setEnabled(true);
 }
}
/**//*
 *客户端
 */
package edu.jlu.fuliang;

import java.io.*;
import java.net.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class Client extends JFrame implements Runnable {
 private Socket client;
 private OutputStream output;
 private InputStream input;
 private Thread outThread;
 private JTextArea display;
 private JTextField text1;
 private JButton startButton;
 private JMenu loginMenu = new JMenu("登录"); 
 private JMenuItem register = new JMenuItem("注册");
 private JMenuItem login = new JMenuItem("登录");
 private JMenuBar bar = new JMenuBar();
 private Register registerDlg ;
 private Login loginDlg;
 private RandomAccessFile file;

 public static void main(String args[]) {
  Client c = new Client();
  c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }

 public Client() {
  super("Client");
  startButton = new JButton("Connect to server");
  text1 = new JTextField(20);
  display = new JTextArea(7, 30);
  display.setEditable(false);
   loginMenu.add(register);
  loginMenu.add(login);
  bar.add(loginMenu);
  setJMenuBar(bar);
  Container container = getContentPane();
  container.setLayout(new BorderLayout());
  container.add(startButton,BorderLayout.NORTH);
  container.add(new JScrollPane(display),BorderLayout.CENTER);
  container.add(text1,BorderLayout.SOUTH);

  try {
     file = new RandomAccessFile(new File("E://login.txt"),"rw");
  } catch (IOException e1) {
   e1.printStackTrace();
  }
  registerDlg = new Register(this,file);
  loginDlg = new Login(this,file);
  startButton.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e) {
    display.setText("连接服务器");
    startButton.setEnabled(false);
    try {
     client = new Socket("127.0.0.1", 5000);
     output = client.getOutputStream();
     input = client.getInputStream();
     outThread = new Thread(Client.this);
     outThread.start();
    } catch (IOException ee) {
    }
   }
  });
  text1.addKeyListener(new KeyAdapter(){
   public void keyPressed(KeyEvent ke) {
   if(ke.getKeyCode() == KeyEvent.VK_ENTER){
    byte writeBytes[] = new byte[50];
    String s = loginDlg.getLoginName()+": " + text1.getText() + "";
    text1.setText("");
    writeBytes = s.getBytes();
    display.append(s+" ");
    try {
     output.write(writeBytes);
    } catch (IOException ee) {
    }
    if (s.trim().equals(loginDlg.getLoginName()+": exit")) {
     outThread.stop();
     quit();
    }
   }
   }
  });
  register.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e) {
    registerDlg.setVisible(true);
   }
  });
  login.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e) {
    loginDlg.setVisible(true);
   }
  });
  setSize(300, 400);
  setResizable(false);
  setVisible(true);
 }

 public void run() {
  while (true) {
   byte readBytes[] = new byte[1024];
   try {
    input.read(readBytes);
   } catch (IOException e) {
   }
   String s = new String(readBytes);
   display.append(s+" ");
   if (s.trim().equals("Server: exit"))
    break;
  }
  quit();
 }

 public void quit() {
  try {
   output.close();
   input.close();
   client.close();
  } catch (IOException e) {
  }
  startButton.setEnabled(true);
 }
}

package edu.jlu.fuliang;

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


public class Login extends JDialog{
 private JTextField textField;
 private JButton loginButton;
 private RandomAccessFile file;//保存注册信息的文件
 private String loginName = "guest";//保存登录者的名字,为登陆为guest;
 
 public Login(JFrame f,RandomAccessFile file){
  super(f,"登陆",false);
  this.file = file;
  JPanel panel = new JPanel();
  panel.add(new JLabel("昵称:"));
  textField = new JTextField(10);
  panel.add(textField);
  Container container = getContentPane();
  container.setLayout(new BorderLayout());
  container.add(panel,BorderLayout.NORTH);
  loginButton = new JButton("登陆");
  container.add(loginButton,BorderLayout.SOUTH);
  setVisible(false);
  setBounds(100,200,200,200);
  loginButton.addActionListener(new LoginListener());
 }
 
 public String getLoginName(){
  return loginName;
 }
 /**//*
  * 登录监听器,当单击登陆按钮时,触发该事件
  * 从文件中读取并查找是否注册过,如果没有找
  * 到则弹出未注册警告。否则弹出欢迎对话框表
  * 示欢迎
  */
 private class LoginListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
  boolean flag = false;
  try {
   String name = textField.getText().trim();
   textField.setText("");
   file.seek(0);
   while(file.getFilePointer() < file.length()){
    String nik = file.readUTF();
    if(nik.equals(name)){
     flag = true;
     loginName = name;
     break;
    }
   }
   if(!flag){
    String warning="没有找到你的账号请先注册!";
             JOptionPane.showMessageDialog(Login.this,warning,"警告",JOptionPane.WARNING_MESSAGE);
   }else{
    String welcome="欢迎来聊天!";
             JOptionPane.showMessageDialog(Login.this,welcome,"欢迎",JOptionPane.WARNING_MESSAGE);
   }
   Login.this.setVisible(false);
  } catch (IOException e1) {
   e1.printStackTrace();
  }
 }
 }
}

package edu.jlu.fuliang;

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


public class Register extends JDialog{
 private String nickName;
 private JTextField textField;
 private JButton registerButton;
 private RandomAccessFile file;////保存注册信息的文件
 
 public Register(JFrame f,RandomAccessFile file){
  super(f,"注册",false);
  this.file = file;
  JPanel panel = new JPanel();
  panel.add(new JLabel("昵称:"));
  textField = new JTextField(10);
  panel.add(textField);
  Container container = getContentPane();
  container.setLayout(new BorderLayout());
  container.add(panel,BorderLayout.NORTH);
  registerButton = new JButton("注册");
  container.add(registerButton,BorderLayout.SOUTH);
  setVisible(false);
  setBounds(100,200,200,200);
  registerButton.addActionListener(new RegisterListener());
 }
 /**//*
  * 注册监听器,当单击登注册按钮时,触发该事件
  * 并向文件中写入注册信息。
  */
 private class RegisterListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
  try {
   file.seek(file.length());
   String  str = textField.getText();
   textField.setText("");
   file.writeUTF(str);
   Register.this.setVisible(false);
  } catch (IOException e1) {
   e1.printStackTrace();
  }
 }
 }
}


你可能感兴趣的:(java,thread,swing,socket,F#)