1901010113 4 роки тому
коміт
80daeb7a6f
33 змінених файлів з 1652 додано та 0 видалено
  1. 104 0
      Readme.MD
  2. 12 0
      SocketDemo.iml
  3. BIN
      out/production/SocketDemo/META-INF/SocketDemo.kotlin_module
  4. BIN
      out/production/SocketDemo/main/Connect/Connect$1.class
  5. BIN
      out/production/SocketDemo/main/Connect/Connect$2.class
  6. BIN
      out/production/SocketDemo/main/Connect/Connect$3.class
  7. BIN
      out/production/SocketDemo/main/Connect/Connect$4.class
  8. BIN
      out/production/SocketDemo/main/Connect/Connect$5.class
  9. BIN
      out/production/SocketDemo/main/Connect/Connect$6.class
  10. BIN
      out/production/SocketDemo/main/Connect/Connect$7.class
  11. BIN
      out/production/SocketDemo/main/Connect/Connect.class
  12. BIN
      out/production/SocketDemo/main/Login/Dialogs4$1.class
  13. BIN
      out/production/SocketDemo/main/Login/Dialogs4.class
  14. BIN
      out/production/SocketDemo/main/Login/Login$1.class
  15. BIN
      out/production/SocketDemo/main/Login/Login$2.class
  16. BIN
      out/production/SocketDemo/main/Login/Login$3.class
  17. BIN
      out/production/SocketDemo/main/Login/Login$4.class
  18. BIN
      out/production/SocketDemo/main/Login/Login.class
  19. BIN
      out/production/SocketDemo/main/Online/online_friend$1$1.class
  20. BIN
      out/production/SocketDemo/main/Online/online_friend$1.class
  21. BIN
      out/production/SocketDemo/main/Online/online_friend$2.class
  22. BIN
      out/production/SocketDemo/main/Online/online_friend$3.class
  23. BIN
      out/production/SocketDemo/main/Online/online_friend.class
  24. BIN
      out/production/SocketDemo/main/Register/Dialogs1$1.class
  25. BIN
      out/production/SocketDemo/main/Register/Dialogs1.class
  26. BIN
      out/production/SocketDemo/main/Register/Register$1.class
  27. BIN
      out/production/SocketDemo/main/Register/Register$2.class
  28. BIN
      out/production/SocketDemo/main/Register/Register.class
  29. 38 0
      sql/users.sql
  30. 435 0
      src/main/Connect/Connect.java
  31. 395 0
      src/main/Login/Login.java
  32. 359 0
      src/main/Online/online_friend.java
  33. 309 0
      src/main/Register/Register.java

+ 104 - 0
Readme.MD

@@ -0,0 +1,104 @@
+`2020-12-28 18:08:38 星期一`
+
+------------
+### 该仓库共有三项目
+### [SocketDemo](http://39.108.133.138:3000/weiyong/202012G09/src/master) - 初版
+### [LinkChat](http://39.108.133.138:3000/weiyong/202012G09/src/linkchat) - 拓展
+### [ChatRoom](http://39.108.133.138:3000/weiyong/202012G09/src/chatroom) - 终版
+------------
+
+# SocketDemo
+
+## 『 环境 』
+
+####  jdk:1.8
+
+#### 数据库 : MySQL5.7
+
+#### 建表如下:
+
+![表](https://s3.ax1x.com/2020/12/28/rTYqbQ.png "表")
+
+#### 注:is_online在线时为1,离线时为0。(默认为0)
+
+## 『 模式 』
+
+#### 采用C/S模式,使得各个客户端通过服务端转发来实现即时通讯的功能。
+
+## 『 思路 』
+
+
+#### 由于202012G09小组的成员都没有服务器
+#### 但我们又有着手实现的迫切需求 于是提出下面的思路:
+
+
+> 如下图:
+
+
+![思路1](https://s3.ax1x.com/2020/12/28/r7kqde.png "思路1")
+
+####  -  将服务端内置到客户端 两端一体
+####  -  每个客户端都成为自己的服务器 则免去中间服务器端
+####  - 如此一来,发送和接收都在本机上不同客户端进行
+
+
+## 『 模块 』
+
+- ### Register(注册)
+  ##### 绘制窗口(注册界面)
+  ##### 实现注册功能
+  	>Tip:
+  		监听注册事件
+  		不能空输入,输入的两次密码必须一致。
+  		插入数据库=>将注册客户的账号密码存储
+  		自动插入前面一位+1的端口
+
+		- Dialogs1:
+		绘制注册验证对话框(确认注册成功并跳转至登录界面)
+
+- ### Login (登录)
+  ##### 绘制窗口(登录界面)
+  ##### 实现登录功能
+  	>Tip:
+  		监听注册按钮
+  		点击注册跳转注册界面
+  		监听登录事件
+  		查询数据库=>验证账号密码及在线状态(存在且离线才能登录)
+  		更新数据库=>更新客户在线/离线状态
+  		查询数据库=>查询客户的服务端端口
+  		开启服务端,开启客户端
+
+		- Dialogs4:
+		绘制登录验证对话框(确认登录成功并跳转至好友列表)
+
+- ### Online (线上)
+   ##### 绘制窗口(好友列表)
+   ##### 实现好友列表
+   >Tip:
+  	监听选择/聊天/退出登录事件
+  	查询数据库=>查询在线用户
+  	显示用户到好友列表
+  	更新数据库=>退出时更新用户在线/离线状态
+  	点击聊天跳转至聊天界面
+
+- ### Connect (连接)
+    ##### 绘制窗口(聊天界面)
+    ##### 实现聊天功能
+    >Tip:
+  	通过多线程分别创建/开启客户端和服务端
+  	客户端连接聊天对象的服务端,服务端连接聊天对象的客户端
+  	循环不断的发送和接收/写入和读取
+  	将接收和发送的数据在界面上显示
+  	断开时关闭聊天功能的一切服务
+
+
+## 『 效果 』
+>![注册](https://s3.ax1x.com/2020/12/30/rqXbPx.png  "注册")
+
+>![登录](https://s3.ax1x.com/2020/12/30/rqXTaR.png "登录")
+
+>![好友列表](https://s3.ax1x.com/2020/12/30/rqX7I1.png "好友列表")
+
+>![聊天]( https://s3.ax1x.com/2020/12/28/rTggrd.png "聊天")
+
+

+ 12 - 0
SocketDemo.iml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="JAVA_MODULE" version="4">
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="library" name="mysql-connector-java-5.1.34-bin" level="project" />
+  </component>
+</module>

BIN
out/production/SocketDemo/META-INF/SocketDemo.kotlin_module


BIN
out/production/SocketDemo/main/Connect/Connect$1.class


BIN
out/production/SocketDemo/main/Connect/Connect$2.class


BIN
out/production/SocketDemo/main/Connect/Connect$3.class


BIN
out/production/SocketDemo/main/Connect/Connect$4.class


BIN
out/production/SocketDemo/main/Connect/Connect$5.class


BIN
out/production/SocketDemo/main/Connect/Connect$6.class


BIN
out/production/SocketDemo/main/Connect/Connect$7.class


BIN
out/production/SocketDemo/main/Connect/Connect.class


BIN
out/production/SocketDemo/main/Login/Dialogs4$1.class


BIN
out/production/SocketDemo/main/Login/Dialogs4.class


BIN
out/production/SocketDemo/main/Login/Login$1.class


BIN
out/production/SocketDemo/main/Login/Login$2.class


BIN
out/production/SocketDemo/main/Login/Login$3.class


BIN
out/production/SocketDemo/main/Login/Login$4.class


BIN
out/production/SocketDemo/main/Login/Login.class


BIN
out/production/SocketDemo/main/Online/online_friend$1$1.class


BIN
out/production/SocketDemo/main/Online/online_friend$1.class


BIN
out/production/SocketDemo/main/Online/online_friend$2.class


BIN
out/production/SocketDemo/main/Online/online_friend$3.class


BIN
out/production/SocketDemo/main/Online/online_friend.class


BIN
out/production/SocketDemo/main/Register/Dialogs1$1.class


BIN
out/production/SocketDemo/main/Register/Dialogs1.class


BIN
out/production/SocketDemo/main/Register/Register$1.class


BIN
out/production/SocketDemo/main/Register/Register$2.class


BIN
out/production/SocketDemo/main/Register/Register.class


+ 38 - 0
sql/users.sql

@@ -0,0 +1,38 @@
+/*
+Navicat MySQL Data Transfer
+
+Source Server         : localhost_3306
+Source Server Version : 50730
+Source Host           : localhost:3306
+Source Database       : socket
+
+Target Server Type    : MYSQL
+Target Server Version : 50730
+File Encoding         : 65001
+
+Date: 2020-12-22 08:27:06
+*/
+
+SET FOREIGN_KEY_CHECKS=0;
+
+-- ----------------------------
+-- Table structure for users
+-- ----------------------------
+DROP TABLE IF EXISTS `users`;
+CREATE TABLE `users` (
+  `id` int(11) NOT NULL AUTO_INCREMENT,
+  `username` varchar(255) NOT NULL,
+  `password` varchar(255) NOT NULL,
+  `is_online` int(255) unsigned NOT NULL,
+  `port` int(255) NOT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
+
+-- ----------------------------
+-- Records of users
+-- ----------------------------
+INSERT INTO `users` VALUES ('1', 'aa', 'aa111111', '1', '18000');
+INSERT INTO `users` VALUES ('2', 'bb', 'bb111111', '1', '18001');
+INSERT INTO `users` VALUES ('3', 'cc', 'cc1111111', '0', '18002');
+INSERT INTO `users` VALUES ('4', 'dd', 'dd111111', '0', '18003');
+INSERT INTO `users` VALUES ('7', 'huawei', '123456', '0', '18004');

+ 435 - 0
src/main/Connect/Connect.java

@@ -0,0 +1,435 @@
+package main.Connect;
+
+import java.awt.EventQueue;
+
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+import java.awt.Font;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Scanner;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+/**
+ * 连接客户端/通话
+ */
+public class Connect extends JFrame {
+
+	private JPanel contentPane;
+	private static JTextField textField;
+	private static JTextArea textArea;
+	private int id;
+	private static String username;
+	private Socket socket;
+	private static Socket socket_server;
+	private static ServerSocket serverSocket;
+	private BufferedReader reader ;
+	private static PrintWriter writer;
+	private static BufferedReader reader_server ;
+	private static PrintWriter writer_server;
+	private static Scanner scanner = new Scanner(System.in);
+	private static Scanner scanner_server = new Scanner(System.in);
+	private static boolean send = false;
+	private static boolean breakdown=false;
+	/**
+	 * Launch the application.
+	 */
+	public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException {
+		// 将SwingUI设置为当前系统的风格
+		String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
+		UIManager.setLookAndFeel(lookAndFeel);
+
+		EventQueue.invokeLater(new Runnable() {
+			public void run() {
+				try {
+					Connect frame = new Connect(2,"bb",serverSocket);
+					frame.setVisible(true);
+				} catch (Exception e) {
+					e.printStackTrace();
+				}
+			}
+		});
+	}
+	
+
+	/**
+	 * Create the frame.
+	 * 绘制窗口(聊天界面)
+	 */
+	public Connect(int id, String username, ServerSocket serverSocket) {
+		setTitle("聊天");
+		this.id=id;
+		this.username=username;
+		this.serverSocket=serverSocket;
+		//关闭窗口时自动隐藏并释放该窗体
+		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+		//设置窗口大小
+		setBounds(100, 100, 503, 500);
+		//设置面板容器
+		contentPane = new JPanel();
+		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
+		setContentPane(contentPane);
+		
+		//设置标签
+		JLabel lblNewLabel = new JLabel("聊 天 内 容");
+		lblNewLabel.setBounds(177, 14, 102, 20);
+		lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 17));
+
+		//设置输入框
+		textField = new JTextField();
+		textField.setBounds(37, 321, 264, 40);
+		textField.setColumns(10);
+
+		//设置发送按钮
+		//默认boolean send = false;
+		JButton btnNewButton = new JButton("发  送");
+		btnNewButton.setBounds(309, 326, 102, 29);
+		btnNewButton.setFont(new Font("宋体", Font.PLAIN, 17));
+		btnNewButton.addActionListener(new ActionListener() {
+			
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				// TODO Auto-generated method stub
+				send=true;
+			}
+		});
+		
+		//设置断开连接按钮
+		JButton btnNewButton_2 = new JButton("断开连接");
+		btnNewButton_2.setBounds(131, 397, 111, 27);
+		btnNewButton_2.addActionListener(new ActionListener() {
+			
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				// TODO Auto-generated method stub
+				breakdown=true;
+			}
+		});
+		
+		
+		
+		
+		contentPane.setLayout(null);
+		//contentPane.add(textArea);
+		contentPane.add(textField);
+		contentPane.add(btnNewButton);
+		contentPane.add(btnNewButton_2);
+		contentPane.add(lblNewLabel);
+
+		//设置滚动面板
+		JScrollPane scrollPane = new JScrollPane();
+		scrollPane.setBounds(37, 48, 383, 240);
+		contentPane.add(scrollPane);
+		
+		textArea = new JTextArea();
+		scrollPane.setViewportView(textArea);
+		
+		//System.out.println("1112");			
+		try {
+			//System.out.println("1113");
+			//int port = getPort(id);
+			
+			runsocket();
+			//System.out.println("1114");	
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		
+		
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				// TODO Auto-generated method stub
+				try {
+					startTheSocket1();
+				} catch (IOException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}
+			}
+		}).start();
+		
+		
+	}
+	
+	
+	
+/////////////////////////////////////////////	
+	
+	public void runsocket() throws IOException{
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				// TODO Auto-generated method stub
+				//System.out.println("1111");
+				try {
+					startTheSocket();
+				} catch (IOException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}
+			}
+			
+		}).start();
+		
+	  }
+
+	  ////////////////////////////////////////客户端
+	  //开始连接服务端
+	  public void startTheSocket() throws IOException{
+	      toConnectTheServer();//创建Socket并初始化
+	      openTheThreadToReceiveInfoFromServer();//开启一个新的线程来接受服务端发来的信息
+	      String yourMessage=" ";
+	      //一个循环,用于读取键盘的输入
+	      while(true) {
+	    	  yourMessage =textField.getText();
+	    	  //String yourMessage = scanner.nextLine();
+	        //不为空则发送信息
+	        if(yourMessage!=null&&send) {
+	          textArea.append("\n"+"你说:"+yourMessage);
+	          writer.println(yourMessage);
+	          writer.flush();//记得flush清空缓冲区
+	          send = false;
+	        //判断是否退出
+		        if (yourMessage.equals("exit")||breakdown) {
+		          disConnect();
+		          //System.exit(0);
+		        }
+	        }
+	        /*//判断是否退出
+	        if (yourMessage.equals("exit")) {
+	          disConnect();
+	          System.exit(0);
+	        }*/
+	      }
+	  }
+	  
+	  
+
+	  //创建一个Socket来连接本机的18080端口的服务端并初始化reader和writer
+	  public void toConnectTheServer() throws IOException {
+		 //System.out.println("id="+id+"\n");
+		int port = getPort(username);
+		System.out.println("port="+port+"\n");
+	    socket=new Socket("127.0.0.1",port);
+	    textArea.append("等待链接!");
+	    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+	    writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
+	  }
+	  
+	 
+	  public void openTheThreadToReceiveInfoFromServer() throws IOException {
+	    new Thread(new Runnable() {
+	      @Override
+	      public void run() {
+	        try {
+	          printMessage();//打印从服务端收到的信息
+	        } catch (IOException e) {
+	          e.printStackTrace();
+	        }
+	      }
+	    }).start();
+	  }
+	 
+	  //循环不断读取服务端的信息
+	  public void printMessage() throws IOException {
+		  boolean flag = false;
+	    while (true) {
+	      String messageFromServer = null;
+	      try {
+	        messageFromServer = reader.readLine();//读取信息
+	        if(messageFromServer.equals("conn")) {
+	        	textArea.append("\n"+"连接成功");
+	        	flag=true;
+	        }
+	       /* if(flag) {
+	        	textArea.append("\n"+username+":"+messageFromServer);
+	        }*/
+	        //System.out.println("He say:" + messageFromServer);//打印信息
+	      } catch (IOException e) {
+	        e.printStackTrace();
+	      } catch (NullPointerException e) {
+	 
+	      }
+	      if(messageFromServer.equals("exit")){
+	        disConnect();//关闭连接
+	        //System.exit(0);
+	      }
+	    }
+	  }
+	 
+	  //关闭各种
+	  public void disConnect() throws IOException {
+	    socket.close();
+	    reader.close();
+	    writer.close();
+	  }
+	
+///////////////////////////////////服务器端
+	  
+	  public static void startTheSocket1() throws IOException {
+		   //serverSocket=new ServerSocket(18000); //打开18080端口等待连接
+		   acceptTheSocket();//接受连接并且初始化Socket,reader,writer
+		   openTheNewThreadToGetMessageFromClient();
+		  /* while(true) {   
+		      getYourMessage();//获取键盘数据并作为输入
+		   }*/
+		   while(true) {
+			   if(breakdown) {
+				   disConnect_server();
+				   breakdown=false;
+				   break;
+			   }
+		   }
+		   
+		 }
+		 
+		 
+		 
+		 
+		 //接受连接并且初始化Socket,reader,writer
+		 private static void acceptTheSocket() throws IOException {
+		   socket_server=serverSocket.accept();//阻塞方法,用于接受Socket连接
+		   System.out.println("Some one connect me ,it is "+socket_server.getLocalSocketAddress());//打印地址
+		   System.out.println("It's port is "+socket_server.getPort());//打印端口号
+		   reader_server = new BufferedReader(new InputStreamReader(socket_server.getInputStream()));//获得输入流
+		   writer_server = new PrintWriter(new OutputStreamWriter(socket_server.getOutputStream()));//获得输出流
+		   String conn = "conn";
+		   writer_server.println(conn);//发送信息
+		   writer_server.flush();//flush方法用于清空缓冲区,注意的是如果不flush你的信息可能发不出去一直存留在缓冲区
+		 }
+		 //扫描键盘并输入数据
+		 private static void getYourMessage() throws IOException {
+		   
+		   //String yourMessage = scanner_server.nextLine();
+			 String yourMessage =textField.getText();
+		   checkYourMessage(yourMessage);//检查发送给客户端的信息
+		   if(send) {
+		   writer.println(yourMessage);//发送信息
+		   writer.flush();//flush方法用于清空缓冲区,注意的是如果不flush你的信息可能发不出去一直存留在缓冲区
+		   }
+		 }
+		 //用于检查是否退出
+		 private static void checkYourMessage(String yourMessage) throws IOException {
+		   //关闭各种
+		   if (yourMessage.equals("exit")) {
+		     socket_server.close();
+		     writer_server.close();
+		     reader_server.close();
+		     System.exit(0);
+		   }
+		 }
+		 //开启一个新的线程来监听客户端发来的信息
+		 private static void openTheNewThreadToGetMessageFromClient() throws IOException {
+		   //开启一个新的线程
+		   new Thread(new Runnable() {
+		     @Override
+		     public void run() {
+		       getTheMessageFromClient();
+		     }
+		   }).start();
+		 
+		 }
+		 //不断循环来获取客户端发来的信息
+		 private static void getTheMessageFromClient() {
+		   while(true) {
+		     String messageFromClient = null;
+		     try {
+		       messageFromClient = reader_server.readLine();
+		     } catch (IOException e) {
+		       e.printStackTrace();
+		     }
+		     printTheMessage(messageFromClient);//打印客户端发来的信息
+		   }
+		 }
+		 //打印客户端发来的信息
+		 private static void printTheMessage(String messageFromClient) {
+		   if(messageFromClient!=null)
+		     //System.out.println("He say:"+messageFromClient);
+			   //textArea.append("\n"+"他说"+":"+messageFromClient);
+			   textArea.append("\n"+username+":"+messageFromClient);
+		 }
+		 
+		 private static void disConnect_server() {
+			 /*try {
+				socket_server.close();
+			} catch (IOException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}*/
+		     writer_server.close();
+		     try {
+				reader_server.close();
+			} catch (IOException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+			 }  
+	  
+///////////////////////////////////	  
+	
+	  public int getPort(String name) {
+			String driver1 = "com.mysql.jdbc.Driver";		
+			String url = "jdbc:mysql://localhost/socket";
+			String username = "root";
+			String password = "123456";
+			Connection conn = null;
+			Statement stmt = null;
+			
+			try{
+			      //STEP 2: Register JDBC driver
+			      Class.forName(driver1);
+			      conn = DriverManager.getConnection(url, username, password);
+			      System.out.println("Connected database successfully...");
+			      stmt = conn.createStatement();
+			      String sql = "select * from users where username = "+"\'"+name+"\'";
+					// 执行 SQL语句
+					// ResultSet 接收查询返回的结果集的一个接口 result 定义的一个接收返回结果的变量名
+			      ResultSet result=null;
+				  result = stmt.executeQuery(sql);
+					// 将查询返回的结果集进行遍历输出
+				  while (result.next()) {
+						// t_id 必须跟数据库的 字段名一致 getInt() 这个 是由对应字段的数据类型决定
+						return Integer.valueOf(result.getString("port"));
+					}
+				  
+			   }catch(SQLException se){
+			      //Handle errors for JDBC
+			      se.printStackTrace();
+			   }catch(Exception e){
+			      //Handle errors for Class.forName
+			      e.printStackTrace();
+			   }finally{
+			      //finally block used to close resources
+			      try{
+			         if(stmt!=null)
+			            conn.close();
+			      }catch(SQLException se){
+			      }// do nothing
+			      try{
+			         if(conn!=null)
+			            conn.close();
+			      }catch(SQLException se){
+			         se.printStackTrace();
+			      }//end finally try
+			   }//end try
+			
+			return -1;
+			
+			
+			//return 1;
+		}
+}

+ 395 - 0
src/main/Login/Login.java

@@ -0,0 +1,395 @@
+package main.Login;
+
+import main.Register.Register;
+import main.Online.online_friend;
+
+import java.awt.Container;
+import java.awt.EventQueue;
+
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+
+import java.awt.FlowLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.ServerSocket;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Scanner;
+
+import javax.swing.GroupLayout.Alignment;
+
+public class Login extends JFrame {
+
+	private JPanel contentPane;
+	private JTextField textField;
+	private JPasswordField passwordField;
+	private  String Username;
+	 private static ServerSocket serverSocket;
+	 private static BufferedReader reader;
+	 private static PrintWriter writer;
+	 private static Scanner scanner = new Scanner(System.in);
+
+	/**
+	 * Launch the application.
+	 */
+	public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException {// Windows Classic风格
+		// 将SwingUI设置为当前系统的风格
+		String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
+		UIManager.setLookAndFeel(lookAndFeel);
+
+		EventQueue.invokeLater(new Runnable() {
+			public void run() {
+				try {
+					Login frame = new Login();
+					frame.setVisible(true);
+				} catch (Exception e) {
+					e.printStackTrace();
+				}
+			}
+		});
+	}
+
+	/**
+	 * Create the frame.
+	 * 绘制窗口(登录界面)
+	 */
+	public Login() {
+		//点击右上角叉叉后只关闭当前界面,其他界面依然显示
+		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+		setBounds(100, 100, 450, 300);
+		setTitle("登录界面");
+		contentPane = new JPanel();
+		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
+		setContentPane(contentPane);
+		setLocationRelativeTo(null);
+
+		JTextPane textPane = new JTextPane();
+		textPane.setText("\u7528\u6237\u540D");
+		
+		JLabel lblNewLabel = new JLabel("\u7528\u6237\u540D\uFF1A");
+		
+		textField = new JTextField();
+		textField.setColumns(10);
+		
+		JLabel lblNewLabel_1 = new JLabel("\u5BC6\u7801\uFF1A");
+		
+		passwordField = new JPasswordField();
+		
+		JButton btnNewButton_1 = new JButton("\u767B\u5F55");
+		
+		btnNewButton_1.addActionListener(new ActionListener() {
+			
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				// TODO Auto-generated method stub
+				//System.out.println("hello");
+				
+				String username=textField.getText();
+				String password= String.valueOf(passwordField.getPassword());
+				if(username!=null&&password!=null) {
+					int mid=getUser(username, password);
+					if(mid!=-1) {
+						Username=username;
+						System.out.println("欢迎登录");
+						boolean mid1 = updateUser(username);
+						int port = getPort(mid);
+						
+						//打开服务端端口
+						try {
+							serverSocket=new ServerSocket(port);
+							System.out.println("开启端口:"+port+"\n");
+						} catch (IOException e1) {
+							// TODO Auto-generated catch block
+							e1.printStackTrace();
+						}
+						
+						
+						online_friend of = new online_friend(mid,username,serverSocket);
+						of.setVisible(true);
+						
+					}
+					else {
+						//System.out.println("用户名或密码错误!");
+						Dialogs4 dlg=new Dialogs4 (null,"用户名或密码错误!");
+						dlg.setLocationRelativeTo(null);
+						dlg.setVisible(true);//显示对话框
+					}
+							
+					
+				}
+				
+														
+			}
+		});
+		
+		JButton btnNewButton_2 = new JButton("\u53D6\u6D88");
+		
+		btnNewButton_2.addActionListener(new ActionListener() {
+			
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				// TODO Auto-generated method stub
+				textField.setText(null);
+				passwordField.setText(null);
+			}
+		});
+		
+		JButton btnNewButton_3 = new JButton("注册");
+		btnNewButton_3.addActionListener(new ActionListener() {
+			
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				// TODO Auto-generated method stub
+				Register reg = new Register();
+				reg.setVisible(true);
+			}
+		});
+		
+		
+		
+		
+		//设置GroupLayout分组布局
+		GroupLayout groupLayout = new GroupLayout(contentPane);
+		groupLayout.setHorizontalGroup(
+			groupLayout.createParallelGroup(Alignment.TRAILING)
+				.addGroup(groupLayout.createSequentialGroup()
+					.addContainerGap(91, Short.MAX_VALUE)
+					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
+						.addComponent(lblNewLabel)
+						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
+							.addComponent(btnNewButton_1, Alignment.TRAILING)
+							.addComponent(lblNewLabel_1)))
+					.addGap(18)
+					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
+						.addGroup(groupLayout.createSequentialGroup()
+							.addGap(157)
+							.addComponent(btnNewButton_3, GroupLayout.PREFERRED_SIZE, 72, GroupLayout.PREFERRED_SIZE))
+						.addGroup(groupLayout.createSequentialGroup()
+							.addGap(35)
+							.addComponent(btnNewButton_2))
+						.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
+							.addComponent(passwordField, Alignment.LEADING)
+							.addComponent(textField, Alignment.LEADING)))
+					.addContainerGap(21, Short.MAX_VALUE))
+		);
+		groupLayout.setVerticalGroup(
+			groupLayout.createParallelGroup(Alignment.LEADING)
+				.addGroup(groupLayout.createSequentialGroup()
+					.addGap(28)
+					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
+						.addGroup(groupLayout.createSequentialGroup()
+							.addGap(32)
+							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
+								.addComponent(lblNewLabel)
+								.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
+							.addGap(26)
+							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
+								.addComponent(lblNewLabel_1)
+								.addComponent(passwordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
+							.addGap(28)
+							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
+								.addComponent(btnNewButton_1)
+								.addComponent(btnNewButton_2)))
+						.addComponent(btnNewButton_3))
+					.addContainerGap(54, Short.MAX_VALUE))
+		);
+		contentPane.setLayout(groupLayout);
+	}
+
+	//从数据库查询用户名/密码
+	public int getUser(String userid,String psd) {
+		
+        String driver1 = "com.mysql.jdbc.Driver";		
+		String url = "jdbc:mysql://localhost:3306/socket";
+		String username = "root";
+		String password = "123456";
+		Connection conn = null;
+		Statement stmt = null;		
+		try{
+		      //STEP 2: Register JDBC driver
+		      Class.forName(driver1);
+		      conn = DriverManager.getConnection(url, username, password);
+		      System.out.println("Connected database successfully...");
+		      stmt = conn.createStatement();
+		      String sql = "select * from users";
+				// 执行 SQL语句
+				// ResultSet 接收查询返回的结果集的一个接口 result 定义的一个接收返回结果的变量名
+		      ResultSet result=null;
+			  result = stmt.executeQuery(sql);
+				// 将查询返回的结果集进行遍历输出
+			  boolean flag=false; 
+			  while (result.next()) {
+					// t_id 必须跟数据库的 字段名一致 getInt() 这个 是由对应字段的数据类型决定
+				  
+					String Userid = result.getString("username");
+					String psd1 = result.getString("password");
+					//System.out.println("id=" + id + "\t" + "name=" + name);
+					if(Userid.equals(userid)&&psd1.equals(psd)) {
+						flag=true;
+						return Integer.valueOf(result.getString("id"));
+						
+					}
+				}
+			  
+		   }catch(SQLException se){
+		      //Handle errors for JDBC
+		      se.printStackTrace();
+		   }catch(Exception e){
+		      //Handle errors for Class.forName
+		      e.printStackTrace();
+		   }finally{
+		      //finally block used to close resources
+		      try{
+		         if(stmt!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		      }// do nothing
+		      try{
+		         if(conn!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		         se.printStackTrace();
+		      }//end finally try
+		   }//end try
+		
+		return -1;
+	}
+	
+//通过数据库更新用户是/否在线状态
+public boolean updateUser(String username1) {
+		
+        String driver1 = "com.mysql.jdbc.Driver";		
+		String url = "jdbc:mysql://localhost/socket";
+		String username = "root";
+		String password = "123456";
+		Connection conn = null;
+		Statement stmt = null;
+		
+		try{
+		      //STEP 2: Register JDBC driver
+		      Class.forName(driver1);
+		      conn = DriverManager.getConnection(url, username, password);
+		      System.out.println("Connected database successfully...");
+		      stmt = conn.createStatement();
+		      String sql = "update users set is_online= 1 where username= "+"\'"+username1+"\'";
+				// 执行 SQL语句
+				// ResultSet 接收查询返回的结果集的一个接口 result 定义的一个接收返回结果的变量名
+		      int result= 0;
+			  result = stmt.executeUpdate(sql);
+				// 将查询返回的结果集进行遍历输出
+			  if(result==1)
+				  return true;
+			  
+		   }catch(SQLException se){
+		      //Handle errors for JDBC
+		      se.printStackTrace();
+		   }catch(Exception e){
+		      //Handle errors for Class.forName
+		      e.printStackTrace();
+		   }finally{
+		      //finally block used to close resources
+		      try{
+		         if(stmt!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		      }// do nothing
+		      try{
+		         if(conn!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		         se.printStackTrace();
+		      }//end finally try
+		   }//end try
+		
+		return false;
+	}
+	
+	
+//从数据库查询用户端口
+public int getPort(int id) {
+	String driver1 = "com.mysql.jdbc.Driver";		
+	String url = "jdbc:mysql://localhost/socket";
+	String username = "root";
+	String password = "123456";
+	Connection conn = null;
+	Statement stmt = null;
+	
+	try{
+	      //STEP 2: Register JDBC driver
+	      Class.forName(driver1);
+	      conn = DriverManager.getConnection(url, username, password);
+	      System.out.println("Connected database successfully...");
+	      stmt = conn.createStatement();
+	      String sql = "select * from users where id = "+id;
+			// 执行 SQL语句
+			// ResultSet 接收查询返回的结果集的一个接口 result 定义的一个接收返回结果的变量名
+	      ResultSet result=null;
+		  result = stmt.executeQuery(sql);
+			// 将查询返回的结果集进行遍历输出
+		  while (result.next()) {
+				// t_id 必须跟数据库的 字段名一致 getInt() 这个 是由对应字段的数据类型决定
+				return Integer.valueOf(result.getString("port"));
+			}
+		  
+	   }catch(SQLException se){
+	      //Handle errors for JDBC
+	      se.printStackTrace();
+	   }catch(Exception e){
+	      //Handle errors for Class.forName
+	      e.printStackTrace();
+	   }finally{
+	      //finally block used to close resources
+	      try{
+	         if(stmt!=null)
+	            conn.close();
+	      }catch(SQLException se){
+	      	// do nothing
+	      }
+	      try{
+	         if(conn!=null)
+	            conn.close();
+	      }catch(SQLException se){
+	         se.printStackTrace();
+	      }//end finally try
+	   }//end try
+	
+	return -1;
+	
+	
+	//return 1;
+}
+	
+	
+	
+	
+}
+
+
+//设置登录验证会话框
+class Dialogs4 extends JDialog{
+	 public Dialogs4(JFrame parent,String show){
+	 super(parent,"登录验证",true);
+	 Container cp=getContentPane();
+	 cp.setLayout(new FlowLayout());
+	 cp.add(new JLabel(show));
+	 JButton ok=new JButton("OK");
+	 ok.addActionListener(new ActionListener(){
+	 public void actionPerformed(ActionEvent e){
+	 dispose();
+	 }
+	 });
+	 cp.add(ok);
+	 setSize(150,125);
+	 }
+	}
+
+
+
+

+ 359 - 0
src/main/Online/online_friend.java

@@ -0,0 +1,359 @@
+package main.Online;
+
+import main.Connect.Connect;
+
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.border.EmptyBorder;
+import javax.swing.JList;
+import javax.swing.GroupLayout;
+import javax.swing.GroupLayout.Alignment;
+import javax.swing.JLabel;
+import java.awt.Font;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.BufferedReader;
+import java.io.PrintWriter;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Scanner;
+
+import javax.swing.JComboBox;
+import javax.swing.JButton;
+
+public class online_friend extends JFrame {
+
+	private JPanel contentPane;
+	private int id1=0;
+	private String username1;
+	private JComboBox comboBox;
+	private Socket socket;
+	private ServerSocket serverSocket;
+	private BufferedReader reader ;
+	private PrintWriter writer;
+	private Scanner scanner = new Scanner(System.in);
+
+	/**
+	 * Launch the application.
+	 */
+
+
+	/**
+	 * Create the frame.
+	 * 绘制窗口(好友列表)
+	 */
+	public online_friend(final int id,final String username,final ServerSocket serverSocket) {
+		id1=id;
+		username1=username;
+		this.serverSocket=serverSocket;
+		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+		setBounds(100, 100, 450, 300);
+		contentPane = new JPanel();
+		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
+		setContentPane(contentPane);
+		setLocationRelativeTo(null);
+		
+		JList list = new JList();
+		
+		JLabel lblNewLabel = new JLabel("在 线 好 友");
+		lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 19));
+		
+		comboBox = new JComboBox();
+		//ResultSet rs = Selectlogin();
+		Selectlogin();
+		
+		
+		JButton btnNewButton = new JButton("聊天");
+		btnNewButton.addActionListener(new ActionListener() {
+			
+			@Override
+			public void actionPerformed(ActionEvent arg0) {
+				// TODO Auto-generated method stub
+				new Thread(new Runnable() {
+
+					@Override
+					public void run() {
+						// TODO Auto-generated method stub
+						String name = (String)comboBox.getSelectedItem();
+						Connect talkframe = new Connect(id1,name,serverSocket);
+						talkframe.setVisible(true);
+					}
+					
+					
+				}).start();
+				
+				/*String name = (String)comboBox.getSelectedItem();
+				Connect talkframe = new Connect(id1,name,serverSocket);
+				talkframe.setVisible(true);*/
+				
+				
+			}
+		});
+
+		JLabel lblNewLabel_1 = new JLabel("选择好友:");
+		lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 17));
+		
+		JButton btnNewButton_1 = new JButton("退出登录");
+		btnNewButton_1.addActionListener(new ActionListener() {
+			
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				// TODO Auto-generated method stub
+				exit(id);
+				
+			}
+		});
+
+		//设置刷新好友列表按钮
+		JButton btnNewButton_2 = new JButton("刷新");
+		btnNewButton_2.addActionListener(new ActionListener() {
+			
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				// TODO Auto-generated method stub
+				comboBox.removeAllItems();
+				Selectlogin();
+			}
+		});
+
+
+		//设置GroupLayout分组布局
+		GroupLayout gl_contentPane = new GroupLayout(contentPane);
+		gl_contentPane.setHorizontalGroup(
+			gl_contentPane.createParallelGroup(Alignment.TRAILING)
+				.addComponent(list, GroupLayout.PREFERRED_SIZE, 422, GroupLayout.PREFERRED_SIZE)
+				.addGroup(gl_contentPane.createSequentialGroup()
+					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
+						.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
+							.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE)
+							.addGap(24))
+						.addGroup(gl_contentPane.createSequentialGroup()
+							.addComponent(lblNewLabel_1, GroupLayout.PREFERRED_SIZE, 87, GroupLayout.PREFERRED_SIZE)
+							.addGap(18)
+							.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING, false)
+								.addComponent(btnNewButton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+								.addComponent(comboBox, Alignment.LEADING, 0, 117, Short.MAX_VALUE))
+							.addGap(57)))
+					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
+						.addComponent(btnNewButton_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+						.addComponent(btnNewButton_2, 0, 0, Short.MAX_VALUE)))
+		);
+		gl_contentPane.setVerticalGroup(
+			gl_contentPane.createParallelGroup(Alignment.LEADING)
+				.addGroup(gl_contentPane.createSequentialGroup()
+					.addComponent(list)
+					.addGap(18)
+					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
+						.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE)
+						.addComponent(btnNewButton_1))
+					.addGap(33)
+					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
+						.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
+						.addComponent(lblNewLabel_1)
+						.addComponent(btnNewButton_2))
+					.addGap(65)
+					.addComponent(btnNewButton)
+					.addContainerGap(49, Short.MAX_VALUE))
+		);
+		contentPane.setLayout(gl_contentPane);
+	}
+	
+
+	//关闭时更新用户状态
+	public boolean locklogin(int id) {			
+	        String driver1 = "com.mysql.jdbc.Driver";		
+			String url = "jdbc:mysql://localhost:3306/socket";
+			String username = "root";
+			String password = "123456";
+			Connection conn = null;
+			Statement stmt2 = null;
+			
+			try{
+			      //STEP 2: Register JDBC driver
+			      Class.forName(driver1);
+			      conn = DriverManager.getConnection(url, username, password);
+			      System.out.println("Connected database successfully...");
+			      stmt2 = conn.createStatement();
+			      String sql = "update users set is_online= 0 where id= "+"\'"+id+"\'";
+			      int result= 0;
+				  result = stmt2.executeUpdate(sql);
+					// 将查询返回的结果集进行遍历输出
+				  if(result==1)
+					  return true;
+				  
+			   }catch(SQLException se){
+			      //Handle errors for JDBC
+			      se.printStackTrace();
+			   }catch(Exception e){
+			      //Handle errors for Class.forName
+			      e.printStackTrace();
+			   }finally{
+			      //finally block used to close resources
+			      try{
+			         if(stmt2!=null)
+			            conn.close();
+			      }catch(SQLException se){
+			      }// do nothing
+			      try{
+			         if(conn!=null)
+			            conn.close();
+			      }catch(SQLException se){
+			         se.printStackTrace();
+			      }//end finally try
+			   }//end try
+			
+			return false;
+		}
+
+	//查询在线用户
+	public void Selectlogin() {
+			
+	        String driver1 = "com.mysql.jdbc.Driver";		
+			String url = "jdbc:mysql://localhost:3306/socket";
+			String username = "root";
+			String password = "123456";
+			Connection conn = null;
+			Statement stmt1 = null;
+			ResultSet result=null;
+			
+			try{
+			      //STEP 2: Register JDBC driver
+			      Class.forName(driver1);
+			      conn = DriverManager.getConnection(url, username, password);
+			      System.out.println("Connected database successfully...");
+			      stmt1 = conn.createStatement();
+			      String sql = "select * from users where is_online = 1";
+				  result = stmt1.executeQuery(sql);
+				  try {
+						while(result.next()) {
+							comboBox.addItem(result.getString("username"));
+						}
+					} catch (SQLException e1) {
+						e1.printStackTrace();
+					}
+
+			   }catch(SQLException se){
+			      //Handle errors for JDBC
+			      se.printStackTrace();
+			   }catch(Exception e){
+			      //Handle errors for Class.forName
+			      e.printStackTrace();
+			   }finally{
+			      //finally block used to close resources
+			      try{
+			         if(stmt1!=null)
+			           conn.close();
+			      }catch(SQLException se){
+			      }// do nothing
+			      try{
+			         if(conn!=null)
+			            conn.close();
+			      }catch(SQLException se){
+			         se.printStackTrace();
+			      }//end finally try
+			   }//end try
+			
+			//return result;
+		}	
+	
+	//退出时恢复用户状态
+	public void exit(int id) {
+		//public boolean updateUser(String username1) {
+			
+	        String driver1 = "com.mysql.jdbc.Driver";		
+			String url = "jdbc:mysql://localhost:3306/socket";
+			String username = "root";
+			String password = "123456";
+			Connection conn = null;
+			Statement stmt1 = null;
+			ResultSet result=null;
+			
+			try{
+			      //STEP 2: Register JDBC driver
+			      Class.forName(driver1);
+			      conn = DriverManager.getConnection(url, username, password);
+			      System.out.println("Connected database successfully...");
+			      stmt1 = conn.createStatement();
+			      String sql = "update users set is_online = 0 where id = "+id;
+				  int mid = stmt1.executeUpdate(sql);
+				  
+			   }catch(SQLException se){
+			      se.printStackTrace();
+			   }catch(Exception e){
+			      e.printStackTrace();
+			   }finally{
+			      try{
+			         if(stmt1!=null)
+			           conn.close();
+			      }catch(SQLException se){
+			      }// do nothing
+			      try{
+			         if(conn!=null)
+			            conn.close();
+			      }catch(SQLException se){
+			         se.printStackTrace();
+			      }//end finally try
+			   }//end try
+		}
+	
+	
+	
+		
+	//获得用户端口
+	public int getPort(int id) {
+		String driver1 = "com.mysql.jdbc.Driver";		
+		String url = "jdbc:mysql://localhost:3306/socket";
+		String username = "root";
+		String password = "123456";
+		Connection conn = null;
+		Statement stmt = null;
+		
+		try{
+		      //STEP 2: Register JDBC driver
+		      Class.forName(driver1);
+		      conn = DriverManager.getConnection(url, username, password);
+		      System.out.println("Connected database successfully...");
+		      stmt = conn.createStatement();
+		      String sql = "select * from users where id = "+id;
+				// 执行 SQL语句
+				// ResultSet 接收查询返回的结果集的一个接口 result 定义的一个接收返回结果的变量名
+		      ResultSet result=null;
+			  result = stmt.executeQuery(sql);
+				// 将查询返回的结果集进行遍历输出
+			  while (result.next()) {
+					// t_id 必须跟数据库的 字段名一致 getInt() 这个 是由对应字段的数据类型决定
+					return Integer.valueOf(result.getString("id"));
+				}
+			  
+		   }catch(SQLException se){
+		      //Handle errors for JDBC
+		      se.printStackTrace();
+		   }catch(Exception e){
+		      //Handle errors for Class.forName
+		      e.printStackTrace();
+		   }finally{
+		      //finally block used to close resources
+		      try{
+		         if(stmt!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		      }// do nothing
+		      try{
+		         if(conn!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		         se.printStackTrace();
+		      }//end finally try
+		   }//end try
+		
+		return -1;
+		
+		
+		//return 1;
+	}
+}

+ 309 - 0
src/main/Register/Register.java

@@ -0,0 +1,309 @@
+package main.Register;
+
+import main.Login.Login;
+
+import java.awt.Container;
+import java.awt.EventQueue;
+import java.awt.FlowLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+
+public class Register extends JFrame {
+
+	private JPanel contentPane;
+	private JTextField textField;
+	private JPasswordField passwordField;
+	private JPasswordField passwordField_1;
+
+	/**
+	 * Launch the application.
+	 */
+	public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException {
+
+		// 当前系统的风格
+		String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
+		UIManager.setLookAndFeel(lookAndFeel);
+
+		EventQueue.invokeLater(new Runnable() {
+			public void run() {
+				try {
+					Register frame = new Register();
+					frame.setVisible(true);
+				} catch (Exception e) {
+					e.printStackTrace();
+				}
+			}
+		});
+	}
+
+	/**
+	 * Create the frame.
+	 * 绘制窗口(注册界面)
+	 */
+	public Register() {
+		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+		setBounds(100, 100, 450, 300);
+		setTitle("注册界面");
+		contentPane = new JPanel();
+		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
+		setContentPane(contentPane);
+		contentPane.setLayout(null);
+		setLocationRelativeTo(null);
+		
+		JLabel lblNewLabel = new JLabel("用户名 :");
+		lblNewLabel.setBounds(114, 40, 85, 18);
+		contentPane.add(lblNewLabel);
+		
+		textField = new JTextField();
+		textField.setBounds(198, 37, 104, 24);
+		contentPane.add(textField);
+		textField.setColumns(10);
+		
+		JLabel lblNewLabel_1 = new JLabel("密  码 :");
+		lblNewLabel_1.setBounds(114, 89, 85, 18);
+		contentPane.add(lblNewLabel_1);
+		
+		passwordField = new JPasswordField();
+		passwordField.setBounds(198, 86, 104, 24);
+		contentPane.add(passwordField);
+		
+		JLabel lblNewLabel_2 = new JLabel("确认密码:");
+		lblNewLabel_2.setBounds(113, 143, 86, 18);
+		contentPane.add(lblNewLabel_2);
+		
+		passwordField_1 = new JPasswordField();
+		passwordField_1.setBounds(198, 140, 104, 24);
+		contentPane.add(passwordField_1);
+		
+		JButton btnNewButton = new JButton("注册");
+		btnNewButton.setBounds(70, 197, 113, 27);
+		contentPane.add(btnNewButton);
+		
+		btnNewButton.addActionListener(new ActionListener() {
+
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				// TODO Auto-generated method stub
+				String userid = textField.getText();
+				String psd1 = String.valueOf(passwordField.getPassword());
+				String psd2 = String.valueOf(passwordField_1.getPassword());
+				//判断输入框内容
+				if (userid.length() == 0 || psd1.length() == 0 || psd2.length() == 0) {
+					Dialogs1 dig = new Dialogs1(null, "请将信息填完整!!!");
+					dig.setVisible(true);
+				}
+
+				else {
+
+					if (psd1.equals(psd2)) {
+						boolean flag = Isregiste(userid);
+						if (flag) {
+							int port = getLastport()+1;
+							Insert_login(userid, psd1, port);
+							Dialogs1 dig = new Dialogs1(null, "注册成功!!!");
+							dig.setVisible(true);
+
+							Login login = new Login();
+							login.setVisible(true);
+						}
+
+						else {
+							Dialogs1 dig = new Dialogs1(null, "用户名已经被注册,请更换其他用户名!");
+							dig.setVisible(true);
+							textField.setText(null);
+							passwordField.setText(null);
+							passwordField_1.setText(null);
+						}
+					}
+
+					else {
+						Dialogs1 dig = new Dialogs1(null, "密码不一致,请重新输入");
+						dig.setVisible(true);
+						textField.setText(null);
+						passwordField.setText(null);
+						passwordField_1.setText(null);
+					}
+
+				}
+
+			}// else
+
+		});
+		
+		//设置取消按钮
+		JButton btnNewButton_1 = new JButton("取消");
+		btnNewButton_1.setBounds(248, 197, 113, 27);
+		contentPane.add(btnNewButton_1);
+						
+	}
+	
+	//插入新用户
+	public static void Insert_login(String userid,String psd,int port) {
+		String driver1 = "com.mysql.jdbc.Driver";		
+		String url = "jdbc:mysql://localhost/socket";
+		String username = "root";
+		String password = "123456";
+		Connection conn = null;
+		Statement stmt = null;		
+		try{
+		      //STEP 2: Register JDBC driver
+		      Class.forName(driver1);
+		      conn = DriverManager.getConnection(url, username, password);
+		      System.out.println("Connected database successfully...");
+		      stmt = conn.createStatement();		     
+		      String sql = "insert into users(username,password,is_online,port) " +
+		                   "values ( "+"\'"+userid +"\'"+" , "+"\'"+psd+"\'"+","+0+","+port+")" ;
+
+		      stmt.executeUpdate(sql);
+		      System.out.println("Successful insert table");
+		   }catch(SQLException se){
+		      //Handle errors for JDBC
+		      se.printStackTrace();
+		   }catch(Exception e){
+		      //Handle errors for Class.forName
+		      e.printStackTrace();
+		   }finally{
+		      //finally block used to close resources
+		      try{
+		         if(stmt!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		      }// do nothing
+		      try{
+		         if(conn!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		         se.printStackTrace();
+		      }//end finally try
+		   }//end try		
+		
+	}
+
+//查询是否被注册
+public boolean Isregiste(String userid) {		
+        String driver1 = "com.mysql.jdbc.Driver";		
+		String url = "jdbc:mysql://localhost:3306/socket";
+		String username = "root";
+		String password = "123456";
+		Connection conn = null;
+		Statement stmt = null;
+		
+		try{
+		      Class.forName(driver1);
+		      conn = DriverManager.getConnection(url, username, password);
+		      System.out.println("Connected database successfully...");
+		      stmt = conn.createStatement();
+		      //STEP 4: Execute a query  
+		      String sql = "select password from users where id = " + "\'"+userid+"\'";
+		      ResultSet result=null;
+			  result = stmt.executeQuery(sql);
+				// 将查询返回的结果集进行遍历输出
+			  while (result.next()) {					
+						String psd1 =result.getString("password");
+						System.out.println( "password=" +psd1 );
+						return false;
+					}
+
+		   }catch(SQLException se){
+		      //Handle errors for JDBC
+		      se.printStackTrace();
+		   }catch(Exception e){
+		      //Handle errors for Class.forName
+		      e.printStackTrace();
+		   }finally{
+		      //finally block used to close resources
+		      try{
+		         if(stmt!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		      }// do nothing
+		      try{
+		         if(conn!=null)
+		            conn.close();
+		      }catch(SQLException se){
+		         se.printStackTrace();
+		      }//end finally try
+		   }//end try
+		
+		return true;
+	}
+
+	//获取最后一个端口并+1
+public int getLastport() {		
+    String driver1 = "com.mysql.jdbc.Driver";		
+	String url = "jdbc:mysql://localhost:3306/socket";
+	String username = "root";
+	String password = "123456";
+	Connection conn = null;
+	Statement stmt = null;
+	int port=-1;	
+	try{
+	      Class.forName(driver1);
+	      conn = DriverManager.getConnection(url, username, password);
+	      System.out.println("Connected database successfully...");
+	      stmt = conn.createStatement();
+	      //STEP 4: Execute a query  
+	      String sql = "select * from users order by id DESC limit 1;";
+	      ResultSet result=null;
+		  result = stmt.executeQuery(sql);
+			// 将查询返回的结果集进行遍历输出
+		  while (result.next()) {					
+					port =Integer.valueOf(result.getString("port"));
+					return port;
+				}
+
+	   }catch(SQLException se){
+	      //Handle errors for JDBC
+	      se.printStackTrace();
+	   }catch(Exception e){
+	      //Handle errors for Class.forName
+	      e.printStackTrace();
+	   }finally{
+	      //finally block used to close resources
+	      try{
+	         if(stmt!=null)
+	            conn.close();
+	      }catch(SQLException se){
+	      }// do nothing
+	      try{
+	         if(conn!=null)
+	            conn.close();
+	      }catch(SQLException se){
+	         se.printStackTrace();
+	      }//end finally try
+	   }//end try
+	
+	return port;
+	}
+}
+
+
+//弹出对话框
+class Dialogs1 extends JDialog{//制作对话框
+	 public Dialogs1(JFrame parent,String show){
+	 super(parent,"登录验证",true);
+	 Container cp=getContentPane();
+	 cp.setLayout(new FlowLayout());
+	 cp.add(new JLabel(show));
+	 JButton ok=new JButton("OK");
+	 ok.addActionListener(new ActionListener(){
+	 public void actionPerformed(ActionEvent e){
+	 dispose();
+	 }
+	 });
+	 cp.add(ok);
+	 setSize(150,125);
+	 }
+}
+
+
+
+