Java采用Socket实现双方即时通信

来源:互联网 发布:sqlserver学习资料 编辑:程序博客网 时间:2024/06/05 19:58
//ChatWindowServer,服务器端聊天窗口
<pre name="code" class="java">package SwingChatServer;import java.awt.EventQueue;import java.awt.Font;import java.awt.GraphicsEnvironment;import java.awt.Point;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JButton;import javax.swing.JTextField;import SwingChatClient.ChatWindowClient;import javax.swing.JTextArea;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class ChatWindowServer extends JFrame{private static final long serialVersionUID = 1031034283370529345L;private JPanel 聊天界面;JTextArea 聊天内容;JTextField 输入内容;JButton 发射;int port = 20000;ServerSocket server;private ServerTh th1;String sendMsg;String receiveMsg;/** * Launch the application. * @throws IOException  */public static void main(String[] args) throws IOException{EventQueue.invokeLater(new Runnable(){public void run(){try{ChatWindowServer frame = new ChatWindowServer();frame.setVisible(true);} catch (Exception e){e.printStackTrace();}}});}/** * Create the frame. */public ChatWindowServer(){setFont(new Font("微软雅黑", Font.PLAIN, 16));setTitle("\u670D\u52A1\u5668");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);GraphicsEnvironment graphics = GraphicsEnvironment.getLocalGraphicsEnvironment();Point p = graphics.getCenterPoint();setBounds((int)p.getX()-300, (int)p.getY()-250, 600, 500);聊天界面 = new JPanel();setContentPane(聊天界面);聊天界面.setLayout(null);//接受自客户端try{server = new ServerSocket(port);th1 = new ServerTh(server);th1.start();}catch (IOException e1){e1.printStackTrace();}发射 = new JButton("发射");发射.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(输入内容.getText() != null){sendMsg = 输入内容.getText();th1.sendMsg(sendMsg);聊天内容.append("我:"+输入内容.getText() + '\n');//按下“发射”键,输入框中的内容添加到聊天框,然后将输入框中的内容清空}输入内容.setText("");}});发射.setFont(new Font("楷体", Font.PLAIN, 20));发射.setBounds(466, 415, 90, 30);聊天界面.add(发射);聊天内容 = new JTextArea();聊天内容.setEditable(false);聊天内容.setFont(new Font("幼圆", Font.PLAIN, 20));聊天内容.setBounds(25, 10, 535, 300);聊天界面.add(聊天内容); 输入内容 = new JTextField();输入内容.addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {if(e.getKeyCode()==KeyEvent.VK_ENTER){发射.doClick();}}});输入内容.setFont(new Font("幼圆", Font.PLAIN, 20));输入内容.setBounds(25, 348, 535, 50);聊天界面.add(输入内容);}//线程内部类class ServerTh extends Thread {ServerSocket server;Socket client;InputStream is;OutputStream os;public ServerTh(ServerSocket server) throws IOException{this.server = server;client = server.accept();System.out.println("客户端接入");is = client.getInputStream();os = client.getOutputStream();}public void run(){while(true){try{byte[] b = new byte[1024];int count = is.read(b);receiveMsg = new String(b,0,count);//添加接收的消息聊天内容.append("对方:"+receiveMsg + '\n');}catch (IOException e){System.out.println("客户端断开连接");break;}}}//本机发送消息public void sendMsg(String msg){try{if(msg != null){os.write(msg.getBytes());os.flush();}}catch (IOException e){System.out.println("与客户端断开连接");}}}}

//LoginFailWindow

package SwingChatServer;import java.awt.BorderLayout;import java.awt.EventQueue;import java.awt.Font;import java.awt.GraphicsEnvironment;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.SwingConstants;import javax.swing.border.EmptyBorder;public class LoginFailWindow extends JFrame{/** * Launch the application. */public static void main(String[] args){EventQueue.invokeLater(new Runnable(){public void run(){try{LoginFailWindow frame = new LoginFailWindow();frame.setVisible(true);}catch (Exception e){e.printStackTrace();}}});}private JFrame 登录失败;private JLabel 账号不存在;private JButton 确定;/** * Create the frame. */public LoginFailWindow(){登录失败 = new JFrame("登录");GraphicsEnvironment graphic = GraphicsEnvironment.getLocalGraphicsEnvironment();Point p = graphic.getCenterPoint();登录失败.setBounds(p.x-150, p.y-100, 300, 200);登录失败.setDefaultCloseOperation(EXIT_ON_CLOSE);登录失败.setVisible(true);登录失败.getContentPane().setLayout(null);账号不存在 = new JLabel("账号不存在");账号不存在.setVerticalAlignment(SwingConstants.TOP);账号不存在.setHorizontalAlignment(SwingConstants.CENTER);账号不存在.setFont(new Font("宋体", Font.PLAIN, 40));账号不存在.setBounds(0, 15, 285, 50);登录失败.getContentPane().add(账号不存在);确定 = new JButton("确定");确定.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {dispose();登录失败.setVisible(false);}});确定.setFont(new Font("楷体", Font.PLAIN, 24));确定.setBounds(80, 80, 120, 60);登录失败.getContentPane().add(确定);}}
//LoginWindow

package SwingChatServer;import java.awt.Font;import java.awt.GraphicsEnvironment;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.ObjectInputStream;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.SwingConstants;import javax.swing.border.EmptyBorder;public class LoginWindow extends JFrame{private static final long serialVersionUID = 5000193009291810531L;private JPanel 登陆界面;JLabel 账号;private JTextField 输入账号;JLabel 密码 ;private JTextField 输入密码;private JButton 注册;private JButton 登陆 ;/** * Create the frame. */public LoginWindow() {setFont(new Font("微软雅黑", Font.PLAIN, 16));setTitle("\u670D\u52A1\u5668\u767B\u9646");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);GraphicsEnvironment graphics = GraphicsEnvironment.getLocalGraphicsEnvironment();Point p = graphics.getCenterPoint();setBounds((int)p.getX()-375, (int)p.getY()-270, 750, 540);登陆界面 = new JPanel();登陆界面.setBorder(new EmptyBorder(5, 5, 5, 5));setContentPane(登陆界面);登陆界面.setLayout(null);setVisible(true);账号 = new JLabel("账号");账号.setHorizontalAlignment(SwingConstants.CENTER);账号.setFont(new Font("楷体", Font.PLAIN, 24));账号.setBounds(150, 90, 124, 58);登陆界面.add(账号);密码 = new JLabel("密码");密码.setHorizontalAlignment(SwingConstants.CENTER);密码.setFont(new Font("楷体", Font.PLAIN, 24));密码.setBounds(150, 190, 124, 58);登陆界面.add(密码);输入账号 = new JTextField();输入账号.setFont(new Font("宋体", Font.PLAIN, 20));输入账号.setBounds(250, 95, 266, 48);登陆界面.add(输入账号);输入账号.setColumns(10);输入密码 = new JTextField();输入密码.setFont(new Font("宋体", Font.PLAIN, 20));输入密码.setColumns(10);输入密码.setBounds(250, 195, 266, 48);登陆界面.add(输入密码);注册 = new JButton("注册");注册.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {setVisible(false);try{new RegistWindow();} catch (IOException e1){e1.printStackTrace();} }});注册.setFont(new Font("楷体", Font.PLAIN, 24));注册.setBounds(165, 360, 120, 60);登陆界面.add(注册);登陆 = new JButton("登陆");登陆.addActionListener(new ActionListener() {private Object user2;public void actionPerformed(ActionEvent e) {try{String str1 = 输入账号.getText();String str2 = 输入密码.getText();UserServer user1 = new UserServer(str1,str2);File src = new File("C:/UserInfo/test1.txt");ObjectInputStream ois = new ObjectInputStream(new FileInputStream(src));try{user2 = (UserServer)ois.readObject();}catch(Exception e1){System.out.println("请输入账号");return;}while(user2 != null){if(user1.equals(user2)){new ChatWindowServer();dispose();setVisible(false);return;}try{user2 = (UserServer)ois.readObject();}catch(IOException e1){System.out.println("请输入账号");//e1.printStackTrace();return;}}new LoginFailWindow();}catch (IOException e1 ){e1.printStackTrace();}catch (ClassNotFoundException e1){e1.printStackTrace();}}});登陆.setFont(new Font("楷体", Font.PLAIN, 24));登陆.setBounds(415, 360, 120, 60);登陆界面.add(登陆);}}

//RegistFailWindow

package SwingChatServer;import java.awt.GraphicsEnvironment;import java.awt.Point;import javax.swing.JFrame;import javax.swing.JLabel;import java.awt.Font;import javax.swing.SwingConstants;import java.awt.BorderLayout;import javax.swing.JButton;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;public class RegistFailWindow extends JFrame{private static final long serialVersionUID = -2495746090511909222L;JFrame frame1;JLabel label1;JButton button;//确定public RegistFailWindow(){frame1 = new JFrame("注册结果");GraphicsEnvironment graphic = GraphicsEnvironment.getLocalGraphicsEnvironment();Point p = graphic.getCenterPoint();frame1.setBounds(p.x-150, p.y-100, 300, 200);frame1.setDefaultCloseOperation(EXIT_ON_CLOSE);frame1.setVisible(true);frame1.getContentPane().setLayout(null);label1 = new JLabel("账号已存在");label1.setVerticalAlignment(SwingConstants.TOP);label1.setHorizontalAlignment(SwingConstants.CENTER);label1.setFont(new Font("宋体", Font.PLAIN, 40));label1.setBounds(0, 15, 285, 50);frame1.getContentPane().add(label1);button = new JButton("确定");button.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {dispose();frame1.setVisible(false);}});button.setFont(new Font("楷体", Font.PLAIN, 24));button.setBounds(80, 80, 120, 60);frame1.getContentPane().add(button);}public static void main(String[] args){new RegistFailWindow();}}

//RegistSuccessWindow

package SwingChatServer;import java.awt.GraphicsEnvironment;import java.awt.Point;import javax.swing.JFrame;import javax.swing.JLabel;import java.awt.Font;import javax.swing.SwingConstants;import java.awt.BorderLayout;import javax.swing.JButton;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;public class RegistSuccessWindow extends JFrame{private static final long serialVersionUID = -2495746090511909222L;JFrame frame1;JLabel label1;JButton button;//确定public RegistSuccessWindow(){frame1 = new JFrame("注册结果");GraphicsEnvironment graphic = GraphicsEnvironment.getLocalGraphicsEnvironment();Point p = graphic.getCenterPoint();frame1.setBounds(p.x-150, p.y-100, 300, 200);frame1.setDefaultCloseOperation(EXIT_ON_CLOSE);frame1.setVisible(true);frame1.getContentPane().setLayout(null);label1 = new JLabel("\u6CE8\u518C\u6210\u529F");label1.setVerticalAlignment(SwingConstants.TOP);label1.setHorizontalAlignment(SwingConstants.CENTER);label1.setFont(new Font("宋体", Font.PLAIN, 40));label1.setBounds(0, 15, 285, 50);frame1.getContentPane().add(label1);button = new JButton("确定");button.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {frame1.setVisible(false);//dispose();}});button.setFont(new Font("楷体", Font.PLAIN, 24));button.setBounds(80, 80, 120, 60);frame1.getContentPane().add(button);}public static void main(String[] args){new RegistSuccessWindow();}}

//RegistWindow

package SwingChatServer;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JLabel;import javax.swing.SwingConstants;import javax.swing.JTextField;import javax.swing.JButton;import java.awt.Font;import java.awt.GraphicsEnvironment;import java.awt.Point;import java.awt.event.ActionListener;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.OutputStream;import java.awt.event.ActionEvent;public class RegistWindow extends JFrame {private static final long serialVersionUID = 5000193009291810531L;private JPanel 注册界面;private JTextField 输入账号;private JTextField 输入密码;private JTextField 确认密码;private JLabel 确认密码2;private JLabel 账号;private JLabel 密码;private JButton 确定;private JButton 取消;File src;InputStream is;ObjectInputStream ois;int flagIsRegisted = 0;//账号是否被注册过的标志位,被注册过则为truepublic RegistWindow() throws IOException {setFont(new Font("微软雅黑", Font.PLAIN, 16));setTitle("注册");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);GraphicsEnvironment graphics = GraphicsEnvironment.getLocalGraphicsEnvironment();Point p = graphics.getCenterPoint();setBounds((int)p.getX()-375, (int)p.getY()-270, 750, 540);注册界面 = new JPanel();注册界面.setBorder(new EmptyBorder(5, 5, 5, 5));setContentPane(注册界面);注册界面.setLayout(null);setVisible(true);src = new File("C:/UserInfo/test1.txt");//数据库if(!src.exists())src.createNewFile();账号 = new JLabel("账号");账号.setHorizontalAlignment(SwingConstants.CENTER);账号.setFont(new Font("楷体", Font.PLAIN, 24));账号.setBounds(160, 70, 124, 58);注册界面.add(账号);密码 = new JLabel("密码");密码.setHorizontalAlignment(SwingConstants.CENTER);密码.setFont(new Font("楷体", Font.PLAIN, 24));密码.setBounds(160, 160, 124, 58);注册界面.add(密码);输入账号 = new JTextField();输入账号.setFont(new Font("宋体", Font.PLAIN, 20));输入账号.setBounds(260, 75, 266, 48);注册界面.add(输入账号);输入账号.setColumns(20);输入密码 = new JTextField();输入密码.setFont(new Font("宋体", Font.PLAIN, 20));输入密码.setColumns(20);输入密码.setBounds(260, 165, 266, 48);注册界面.add(输入密码);确认密码 = new JTextField();确认密码.setFont(new Font("宋体", Font.PLAIN, 20));确认密码.setColumns(20);确认密码.setBounds(260, 255, 266, 48);注册界面.add(确认密码);确定 = new JButton("确定");确定.setFont(new Font("楷体", Font.PLAIN, 24));确定.setBounds(165, 360, 120, 60);注册界面.add(确定);//先不比对,直接注册输入的账号确定.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {try{String str1 = 输入账号.getText();String str2 = 输入密码.getText();UserServer temp2 = new UserServer(str1,str2);//当第一次写入文件时,检测文件长度,长度小于1则直接写入,使用ObjectOutputStream的writeObject()方法,写入对象包含头文件if(src.length()<1){System.out.println("可以注册");OutputStream os = new FileOutputStream(src,true);ObjectOutputStream oos = new ObjectOutputStream(os);oos.writeObject(temp2);oos.flush();oos.close();System.out.println("注册成功");new RegistSuccessWindow();}//文件长度大于1,即追加写入时,调用MyObjectOutputStream的writeObject()方法,//因为MyObjectOutputStream重写了writeStreamHeader(),不再写入头文件,这样ObjectInputStream才能连续读取对象else{is = new FileInputStream(src);ois = new ObjectInputStream(is);UserServer temp1 = (UserServer) ois.readObject();while(true){System.out.println(temp1.toString());if(temp1.equals(temp2)){new RegistFailWindow();ois.close();return;}try{temp1 = (UserServer) ois.readObject();}catch(Exception e1){System.out.println("读完文件");break;}}ois.close();if(!输入密码.getText().equals(确认密码.getText())){System.err.println("两次输入的密码不同");}else{System.out.println("可以注册");OutputStream os = new FileOutputStream(src,true);MyObjectOutputStream oos = new MyObjectOutputStream(os);oos.writeObject(temp2);oos.flush();oos.close();System.out.println("注册成功");new RegistSuccessWindow();}}}catch(Exception e1){e1.printStackTrace();}}});取消 = new JButton("取消");取消.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {setVisible(false);new LoginWindow();}});取消.setFont(new Font("楷体", Font.PLAIN, 24));取消.setBounds(415, 360, 120, 60);注册界面.add(取消);确认密码2 = new JLabel("\u786E\u8BA4\u5BC6\u7801");确认密码2.setHorizontalAlignment(SwingConstants.CENTER);确认密码2.setFont(new Font("楷体", Font.PLAIN, 24));确认密码2.setBounds(135, 245, 124, 58);注册界面.add(确认密码2);}//判断账号是否被注册public boolean isRegisted(String str){if (输入账号.getText().trim() == null)//取得输入的账号字符串,去掉首尾的空格{return false;} else if (!输入账号.getText().equals(str))return false;return true;}}class MyObjectOutputStream extends ObjectOutputStream{public MyObjectOutputStream() throws IOException, SecurityException{super();}public MyObjectOutputStream(OutputStream os) throws IOException, SecurityException{super(os);}protected void writeStreamHeader() throws IOException{return;}}

//User

package SwingChatServer;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.OutputStream;import java.io.Serializable;public class UserServer implements Serializable{private static final long serialVersionUID = 4791580772128277344L;String name;String password;public UserServer(String name,String password){this.name = name;this.password = password;}public String toString(){return "用户名:"+this.name+" ----密码:"+this.password;}public boolean equals(Object obj){if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;UserServer other = (UserServer) obj;if (name == null){if (other.name != null)return false;} else if (!name.equals(other.name))return false;if (password == null){if (other.password != null)return false;} else if (!password.equals(other.password))return false;return true;}public static void main(String[] args) throws IOException, ClassNotFoundException{File src = new File("C:/UserInfo/test1.txt");//OutputStream os = new FileOutputStream(src,true);//ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(src,true));//User a = new User("a","123");User b = new User("b","123");//User c = new User("c","123");User d = new User("d","123");//User e = new User("e","123");User f = new User("f","123");//User g = new User("g","123");User h = new User("h","123");//oos.writeObject(a);oos.writeObject(b);oos.writeObject(c);oos.writeObject(d);//oos.writeObject(e);oos.writeObject(f);oos.writeObject(g);oos.writeObject(h);//oos.writeObject(null);//oos.close();InputStream is = new FileInputStream(src);ObjectInputStream ois = new ObjectInputStream(is);UserServer test = (UserServer)ois.readObject();while(test != null){System.out.println(test.toString());try{test = (UserServer)ois.readObject();}catch(IOException e){break;}}ois.close();}}

//test

package SwingChatServer;public class test{public static void main(String[] args){LoginWindow a = new LoginWindow();}}


0 0