|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 |
package
com.tcp;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.net.Socket;/** * 客户端 * @author Administrator * */public
class ClientTcp { public
static void main(String[] args) { /** * 模拟客户端,给tomcat发送请求(请记得把你的tomcat启动) *1.创建socket *2.设置连接和端口,端口号为tomcat的端口号8080 */ Socket socket = null; try
{ socket = new
Socket("127.0.0.1", 8080); PrintWriter pw = new
PrintWriter(socket.getOutputStream(), true); InputStream inputStream = socket.getInputStream(); byte[] bytes1 = new
byte[1024]; int
count = 0; pw.println("GET / HTTP/1.1"); pw.println("Host: localhost:8080"); pw.println("Connection: keep-alive"); pw.println("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); pw.println("User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.3.1.2000 Chrome/30.0.1599.101 Safari/537.36"); pw.println("DNT: 1"); pw.println("Accept-Encoding: gzip,deflate"); pw.println("Accept-Language: zh-CN"); pw.println();//这个空行是结束标记 //接收 while((count = inputStream.read(bytes1)) != -1){ String back = new
String(bytes1, 0, count); System.out.println(back); } } catch
(IOException e) { e.printStackTrace(); }finally{ try
{ if(socket != null){ socket.close(); } } catch
(IOException e) { e.printStackTrace(); } } }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54 |
package
com.tcp;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;/** * 服务端,模拟服务器 * @author Administrator * */public
class ServerTcp { /** * 1.创建服务 * 2.获取socket,输入流 * @param args */ public
static void main(String[] args) { ServerSocket ss = null; try
{ //接收 ss = new
ServerSocket(10000); Socket socket = ss.accept();//阻滞式的 //while循环是为了让服务器不停止 while(true){ InputStream is = socket.getInputStream(); byte[] bytes = new
byte[1024]; int
count = 0; //这个while循环,会卡住 while((count = is.read(bytes)) != -1){ String str = new
String(bytes, 0, count); //这里仅打印浏览器发来的信息 System.out.println(str); } } } catch
(IOException e) { e.printStackTrace(); }finally{ if(ss != null){ try
{ ss.close(); } catch
(IOException e) { e.printStackTrace(); } } } }} |
原文:http://www.cnblogs.com/lxricecream/p/3651385.html