理解socket
java的socket中的ServerSocket提供固定位置的访问。比如我们访问一个服务器http://java-er.com 其实是对java-er.com这台机器上固定80端口的访问。
下面看个小例子。这个例子你在Eclipse里启动这个程序,就可以在浏览器里直接访问并会有数据打印在浏览器上。
package com.javaer.examples.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("server start");
ServerSocket server = new ServerSocket(2156);
Socket client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
int i = 0;
while (true) {
String str = in.readLine();//接受客户方输入字符串
System.out.println(str);
i++;
out.println("has receive...." + i);//回传给客户端
out.flush();
if(str.indexOf("Accept-Charset:")!=-1){ //用于网页请求鉴定
break;
}
if (str.equals("end"))//接收到客户端输入end, 表示停止回话
break;
}
client.close();
}
}
启动以后,在浏览器里输入http://localhost:2156
GET / HTTP/1.1
Host: localhost:2156
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8
Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3
你懂了吗?