forked from CPU-Code/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServertcp1.java
More file actions
51 lines (42 loc) · 1.52 KB
/
Servertcp1.java
File metadata and controls
51 lines (42 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* @由于个人水平有限, 难免有些错误, 还请指点:
* @Author: cpu_code
* @Date: 2020-09-19 22:28:11
* @LastEditTime: 2020-09-19 22:31:31
* @FilePath: \java\network\Servertcp1.java
* @Gitee: [https://gitee.com/cpu_code](https://gitee.com/cpu_code)
* @Github: [https://github.com/CPU-Code](https://github.com/CPU-Code)
* @CSDN: [https://blog.csdn.net/qq_44226094](https://blog.csdn.net/qq_44226094)
* @Gitbook: [https://923992029.gitbook.io/cpucode/](https://923992029.gitbook.io/cpucode/)
*/
package network;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Servertcp1 {
public static void main(String[] args) throws IOException {
System.out.println("服务器启动, 等待连接");
// 1.创建 ServerSocket 对象,绑定端口,开始等待连接
ServerSocket ss = new ServerSocket(666);
// 2.接收连接 accept 方法, 返回 socket 对象.
Socket server = ss.accept();
// 3.通过socket 获取输入流
InputStream is = server.getInputStream();
// 4.一次性读取数据
// 4.1 创建字节数组
byte[] b = new byte[1024];
// 4.2 据读取到字节数组中
int len = is.read(b);
// 4.3 解析数组,打印字符串信息
String msg = new String(b, 0, len);
System.out.println(msg);
//5.关闭资源
is.close();
server.close();
}
}
/*
服务器启动, 等待连接
你好 cpucode
*/