008socket基本使用

    技术2022-07-11  65

    package sock1; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class MySock8 { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(12121); while (true) { Socket accept = serverSocket.accept(); System.out.println(accept.getInetAddress().getHostAddress()); PrintWriter printWriter = new PrintWriter(accept.getOutputStream(), true); InputStream inputStream = accept.getInputStream(); byte[] bytes = new byte[1234]; int read = inputStream.read(bytes); System.out.println("read = " + read); System.out.println(new String(bytes,0,read)); printWriter.println("<h1>hello and welcome!</h1>"); accept.close(); } } } class MyClient{ public static void main(String[] args) throws Exception { String str = "http://127.0.0.1:8080/mypac/abc.html"; int beginIndex = str.indexOf("//") + 2; int i = str.indexOf("/", beginIndex); String address = str.substring(beginIndex, i); String path = str.substring(i); System.out.println("address = " + address); System.out.println("path = " + path); String[] split = address.split(":"); System.out.println(split[0]); System.out.println(Integer.parseInt(split[1])); Socket socket = new Socket("127.0.0.1", 8080); PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); printWriter.println("GET /mypac/abc.html HTTP/1.1"); printWriter.println("Accept: text/html, application/xhtml+xml, image/jxr, */*"); printWriter.println("Accept-Language: zh-Hans-CN,zh-Hans;q=0.5"); printWriter.println("Host: 127.0.0.1:12121"); printWriter.println("Connection: Keep-Alive"); printWriter.println(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"gbk")); String line =null; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } socket.close(); } } //GET /mypac/abc.html HTTP/1.1 // Accept: text/html, application/xhtml+xml, image/jxr, */* //Accept-Language: zh-Hans-CN,zh-Hans;q=0.5 //User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586 //Accept-Encoding: gzip, deflate //Host: 127.0.0.1:12121 //Connection: Keep-Alive
    Processed: 0.011, SQL: 9