标签:class 简易 write input public type soc str server
-----2019-9-29----------
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(89);
System.out.println("Server started at " + new Date() + "\n");
while (true) {
// 通信socket的获得
Socket socket = serverSocket.accept();
System.out.println("client connected...");
//读取数据
InputStream in = socket.getInputStream();
byte[] b = new byte[512];
int len = in.read(b);
String s = new String(b, 0, len);
System.out.println("" + socket.getInetAddress() + " " + socket.getPort());
System.out.println(s);
//返回数据
String res = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"\r\n" +
"<html>\r\n" +
"<head>\r\n"+
"<title>HTTP Server</title>\r\n" +
"</head>\r\n" +
"<body>\r\n" +
"Hello HTTP!\r\n"+
"</body>\r\n" +
"</html>";
OutputStream out = socket.getOutputStream();
out.write(res.getBytes());
//关闭连接,会将in和out一起关闭
socket.close();
System.out.println("connection closed...");
System.out.println();
}
serverSocket.close();//ide会报错无法执行到这一行,注释掉就行
}
}
标签:class 简易 write input public type soc str server
原文地址:https://www.cnblogs.com/cdbb/p/12558107.html