写一个 MyServerSocket 程序, 用来接收 8081 端口的请求信息.
package com.javalearn.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServerSocket {
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket serverSocket = null;
Socket clientSocket = null;
BufferedReader br = null;
try {
// 服务器套接字, 使用 8081 端口
serverSocket = new ServerSocket(8081);
// 由服务器套接字生成 套接字 对象, 开始监听网络, 等待接收客户端消息
clientSocket = serverSocket.accept();
// 接收 客户端套接字 消息
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// 消息打印
String temp = null;
while((temp = br.readLine()) != null) {
System.out.println(temp);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 资源关闭
if (br != null) {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
写一个 MyClientSocket 程序, 用来测试上面的服务器套接字.
package com.javalearn.socket;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MyClientSocket {
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket = null;
PrintWriter out = null;
try {
// 客户端套接字 对象
socket = new Socket("localhost", 8081);
// 输出流 对象
out = new PrintWriter(socket.getOutputStream());
// 输出信息
String msg = "Fast Fox";
// 传输
out.print(msg);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 资源关闭
if (out != null) {
out.close();
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
其实下面的测试程序不写也行, 直接在本机的浏览器地址栏输入类似 http://127.0.0.1:8081/index.html 地址后回车即可在控制台看到对应的消息.