Service端
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
socket.setSoTimeout(20000);
OutputStream out = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
Reader reader = new InputStreamReader(inputStream);
char chars[] = new char[512];
int len;
while ((len = reader.read(chars)) != -1) {
String str = new String(chars, 0, len);
System.out.println(str);
}
System.out.println("--------------------");
socket.close();
}
Client 端
public static void main(String[] args) throws Exception {
URL url = new URL("http://127.0.0.1:9999/work");
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
OutputStream out = con.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
out.write("Hello World".getBytes());
out.flush();
// String line = "";
// for (line = br.readLine(); line != null; line = br.readLine()) {
// System.out.println(line);
// }
out.close();
}
Server端输出:
POST /work HTTP/1.1
User-Agent: Java/1.6.0_45
Host: 127.0.0.1:9999
Accept: text/html, image/gif, image/jpeg, ; q=.2, */; q=.2
Connection: keep-alive
Content-type: application/x-www-form-urlencoded
Content-Length: 0
没有输出Hello World! 求解
http://blog.csdn.net/yanzi1225627/article/details/22222735
你这样改一下,service端口先处理inputstream,后处理outputstream;client端先处理outputstream,后处理inputstream。
Client 改成这样 拿到了
public static void main(String[] args) throws Exception {
URL url = new URL("http://127.0.0.1:9999/work");
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
OutputStream out = con.getOutputStream();
out.write("Hello World".getBytes());
out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
out.close();
}
谢 2楼