1. 基本Socket链接
Socket s = new Socketserver, port);
try {
InputStream inStream = s.getInputStream();
Scanner in = new Scanner(inStream);
while (in.hasNextLine()) {
String line = in.nextLine();
}
} finally {
s.close();
}
2. 服务器编写
ServerSocket s = new ServerSocket(port);
Socket incoming = s.accept();
try {
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
Scanner in = new Scanner(inStream);
PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);
out.println("Hello! Enter BYE to exit.");
boolean done = false;
while (!done && in.hasNextLine()) {
String line = in.nextLine();
out.println("Echo: " + line);
if (line.trim().equals("BYE")) {
done = true;
}
}
} finally {
incoming.close();
}
3. 提供多线程访问的服务器
ServerSocket s = new ServerSocket(port);
while(true) {
Socket incoming = s.accept();
Runnable r = new ThreadedEchoHandler(incoming);
Thread t = new Thread(r);
t.start();
}
class ThreadedEchoHandler implements Runnable {
public ThreadedEchoHandler(Socket i) {
incoming = i;
}
public void run() {like up}
}
4. 发送Mail
Socket s = new Socket(mailServerName, port);
InputStream inStream = s.getInputStream();
OutputStream outStream = s.getOutputStream();
in = new Scanner(inStream);
out = new PrintWriter(outStream, true /* autoFlush */);
String hostName = InetAddress.getLocalHost().getHostName();
receive();
send("HELO " + hostName);
receive();
send("MAIL FROM: <" + from.getText() + ">");
receive();
send("RCPT TO: <" + to.getText() + ">");
receive();
send("DATA");
receive();
send(message.getText());
send(".");
receive();
s.close();
public void send(String s) throws IOException {
comm.append(s);
comm.append("\n");
out.print(s.replaceAll("\n", "\r\n"));
out.print("\r\n");
out.flush();
}
public void receive() throws IOException {
if (in.hasNextLine()) {
String line = in.nextLine();
comm.append(line);
comm.append("\n");
}
}
5. 通过URL连接获取服务器信息
URL url = new URL(urlName); //新建URL对象
URLConnection connection = url.openConnection(); //打开URL连接
connection.setRequestProperty("Authorization", "Basic " + encoding); //设置用户名和密码访问属性
connection.connect(); //开始连接
Map<String, List<String>> headers = connection.getHeaderFields(); //返回header的所有键值对
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey(); //得到键
for (String value : entry.getValue())
System.out.println(key + ": " + value); //得到值
}
System.out.println("getContentType: " + connection.getContentType()); //获取内容类型,比如text/plain
System.out.println("getContentLength: " + connection.getContentLength()); //返回内容长度
System.out.println("getContentEncoding: " + connection.getContentEncoding()); //获取内容编码,比如gzip
System.out.println("getDate: " + connection.getDate()); //获取创建时间
System.out.println("getExpiration: " + connection.getExpiration()); //获取过期时间
System.out.println("getLastModifed: " + connection.getLastModified()); //获取最后修改时间
Scanner in = new Scanner(connection.getInputStream());
for (int n = 1; in.hasNextLine() && n <= 10; n++) //打印前10行内容
System.out.println(in.nextLine());
6. 提交表单到服务器
GET方式: 将参数附在URL结尾,空格由+来代替,但是参数长度有限制
POST方式: 通过表单进行数据提交
注意: URLEncoder具有encode(String s, String encoding)和decode(String s, String encoding)方法
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.setDoOutput(true); //建立一个用于输出的连接
PrintWriter out = new PrintWriter(connection.getOutputStream()); //使用该流向服务器发信息
boolean first = true;
for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
if (first) first = false;
else out.print('&');
String name = pair.getKey();
String value = pair.getValue();
out.print(name);
out.print('=');
out.print(URLEncoder.encode(value, "UTF-8"));
} //向输出流加入参数
out.close();
//得到返回信息
Scanner in;
StringBuilder response = new StringBuilder();
try {
in = new Scanner(connection.getInputStream());
} catch (IOException e) {
if (!(connection instanceof HttpURLConnection)) throw e;
InputStream err = ((HttpURLConnection)connection).getErrorStream();
if (err == null) throw e;
in = new Scanner(err);
}
while (in.hasNextLine()) {
response.append(in.nextLine());
response.append("\n");
}
in.close();
return response.toString();
7. 套接字超时
SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", 8189)); //超时或者中断,会有InterrputedException抛出
8. 半关闭
当一个请求给服务器发送信息,服务器必须知道该请求什么时候结束,所以需要关闭一个套接字的输出流,来表示数据已经发送结束
Socket socket = new Socket(host, port);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.print(...);
writer.flush();
socket.shutdownOutput(); //关闭输出流
while (in.hasNextLine() != null) {String line = in.nextLine();} //读返回数据
socket.close(); //关闭整个socket
9. 通过主机名得到IP地址
InetAddress[] address = InetAddress.getAllByName(host); //有时主机名对应的地址不止一个,所以用数组来获取
for (InetAddress a : address) print address
InetAddress address = InetAddress.getLocalHost(); //得到本机地址,而不是127.0.0.1,而是对外的IP地址