使用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 協(xié)議
printWriter.println("Host: localhost"); //Host請(qǐng)求頭
printWriter.println("Connection: Close");//關(guān)閉連接
printWriter.println(); //Http請(qǐng)求的格式
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 服務(wù)端
@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("回復(fù)給你的消息");
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();
}
}