Created
January 2, 2020 08:48
-
-
Save xialeistudio/4ed50740e9e49eddff98e20c69f24a0f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```java | |
package com.ddhigh.learn; | |
import java.io.*; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
ServerSocket ss = new ServerSocket(10000, 128); | |
System.out.println("listen on port: 10000. backlog=128"); | |
while (true) { | |
Socket s = ss.accept(); | |
Thread t = new Thread(new ClientThread(s)); | |
t.start(); | |
} | |
} | |
static class ClientThread implements Runnable { | |
private Socket client; | |
public ClientThread(Socket client) { | |
this.client = client; | |
} | |
@Override | |
public void run() { | |
System.out.printf("[Thread-%s] %s connected\n", Thread.currentThread().getName(), client.getRemoteSocketAddress()); | |
try ( | |
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); | |
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream())) | |
) { | |
this.handshake(bw, br); | |
// 开始正常逻辑交互 | |
bw.write("HELLO WORLD!\n"); | |
bw.flush(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
System.out.printf("[Thread-%s] %s disconnected\n", Thread.currentThread().getName(), client.getRemoteSocketAddress()); | |
} | |
} | |
/** | |
* 握手 | |
* | |
* @param bw | |
* @param br | |
* @throws IOException | |
*/ | |
private void handshake(BufferedWriter bw, BufferedReader br) throws IOException { | |
// 检测账号 | |
while (true) { | |
bw.write("username:\n"); | |
bw.flush(); | |
String username = br.readLine(); | |
if (username.isEmpty() || !username.equals("xialei")) { | |
bw.write("username invalid.\n"); | |
bw.flush(); | |
continue; | |
} | |
break; | |
} | |
// 检测密码 | |
while (true) { | |
bw.write("password:\n"); | |
bw.flush(); | |
String password = br.readLine(); | |
if (password.isEmpty() || !password.equals("111111")) { | |
bw.write("password invalid.\n"); | |
bw.flush(); | |
continue; | |
} | |
break; | |
} | |
// 握手完成 | |
bw.write("handshake ok\n"); | |
bw.flush(); | |
} | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment