使用socket连接
try(Socket socket=new Socket("127.0.0.1",8988)){
final InputStream inputStream = socket.getInputStream();
final OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter=new PrintWriter(outputStream,true);
printWriter.println("GET /hello.txt HTTP/1.1");//GET url 协议
printWriter.println("Host: localhost"); //Host请求头
printWriter.println("Connection: Close");//关闭连接
printWriter.println(); //Http请求的格式
BufferedReader bufferedReader=new BufferedReader(
new InputStreamReader(inputStream,"GBK")
);
boolean getting=true;
StringBuffer sb=new StringBuffer();
while (getting){
if(bufferedReader.ready()){
int b=bufferedReader.read();
while (b!=-1){
sb.append((char)b);
b=bufferedReader.read();
}
getting=false;
}
}
System.out.print(sb);
}catch (Exception ignored){
}
使用socket 服务端
@Test
public void socketServer(){
try (ServerSocket serverSocket=new ServerSocket(8886)){
Socket accept = serverSocket.accept();//等待连接
final OutputStream outputStream = accept.getOutputStream();//接收到连接后返回的值
PrintWriter printWriter=new PrintWriter(outputStream,true);
printWriter.println("回复给你的消息");
printWriter.flush();
printWriter.close();
}catch (Exception e){
e.printStackTrace();
}
}
使用socket客户端
@Test
public void socketClient(){
try (Socket socket=new Socket("127.0.0.1",8886)){
final OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter=new PrintWriter(outputStream);
printWriter.println("GET / HTTP/1.1");
printWriter.println("Host: localhost");
printWriter.println("Connection: Close");
printWriter.println();
final InputStream inputStream = socket.getInputStream();
Scanner scanner=new Scanner(inputStream, "utf-8");
while (scanner.hasNextLine()){
System.out.print(scanner.nextLine());
}
System.out.println();
System.out.println("获取信息完毕~");
}catch (Exception e){
e.printStackTrace();
}
}
网友评论