Java socket简单服务端客户端
package com.www.socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* @author 47144
*/
public class ServerDemo {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("serverSocket is running");
while (true){
Socket socket = serverSocket.accept();
System.out.println("connected from "+socket.getRemoteSocketAddress());
Thread t = new Handle(socket);
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Handle extends Thread{
private Socket socket;
public Handle(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try (InputStream inputStream = this.socket.getInputStream()) {
try (OutputStream outputStream = this.socket.getOutputStream()) {
handle(inputStream, outputStream);
}
} catch (Exception e) {
e.printStackTrace();
try {
this.socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("client disconnected!");
}
}
private void handle(InputStream inputStream, OutputStream outputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,StandardCharsets.UTF_8));
// 读取http请求
boolean requestOk = false;
String firstLine = bufferedReader.readLine();
if (firstLine.startsWith("GET / HTTP/1.")){
requestOk= true;
}
for (;;){
String header = bufferedReader.readLine();
if (header.isEmpty()){
break;
}
System.out.println(header);
}
System.out.println(requestOk?"Response OK":"Response ERROR");
if (!requestOk){
bufferedWriter.write("HTTP/1.0 404 Not Found\r\n");
bufferedWriter.write("Content-Length: 0\r\n");
bufferedWriter.write("\r\n");
bufferedWriter.flush();
}else {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\47144\\IdeaProjects\\mybatiStudy\\mybatis-01\\src\\main\\java\\com\\www\\socket\\a.html"));
StringBuilder data = new StringBuilder();
String line = null;
while ((line=reader.readLine())!=null){
data.append(line);
}
reader.close();
int length = data.toString().getBytes(StandardCharsets.UTF_8).length;
bufferedWriter.write("HTTP/1.1 200 OK\r\n");
bufferedWriter.write("Connection: keep-alive OK\r\n");
bufferedWriter.write("Content-Type: text/html\r\n");
bufferedWriter.write("Content-Length: "+length+"\r\n");
bufferedWriter.write("\r\n");
bufferedWriter.write(data.toString());
data.delete(0,data.length());
bufferedWriter.flush();
}
}
}