Java Socket构建阻塞的TCP通信
时间:2011-07-22 “子 孑” 博客
1.服务器端
1.创建ServerSocket对象,可在构造子中指定监听的端口;
private int port = 8000;
private ServerSocket serverSocket;
……
serverSocket = new ServerSocket(port);
2.服务器端调用ServerSocket对象的accept()方法,该方法一直监听端口,等待客户的连接请求,如 果接收到一个连接请求,accept()方法就会返回一个Socket对象,这个Socket对象与客户端的Socket对象 将形成一条通信线路;
Socket socket = null;
socket = serverSocket.accept(); // 等待客户连接
3.Socket类提供了getInputStream()方法和getOutputStream()方法。
InputStream socketIn = socket.getInputStream();
OutputStream socketOut = socket.getOutputStream();
源代码EchoServer.java
public class EchoServer {
private int port = 8000;
private ServerSocket serverSocket;
public EchoServer() throws IOException {
serverSocket = new ServerSocket(port);
System.out.println("Server Start");
}
public String echo(String msg) {
return "echo:" + msg;
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut, true);
}
private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public void service() {
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept(); // 等待客户连接
System.out.println("New connection accepted "
+ socket.getInetAddress() + ":" + socket.getPort());
BufferedReader br = getReader(socket);
PrintWriter pw = getWriter(socket);
String msg = null;
while ((msg = br.readLine()) != null) {
System.out.println(msg);
pw.println(echo(msg));
if (msg.equals("bye")) // 如果客户发送的消息为“bye”,就结束通信
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null)
socket.close(); // 断开连接
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]) throws IOException {
new EchoServer().service();
}
}
Java Socket构建阻塞的TCP通信(2)
时间:2011-07-22 “子 孑” 博客
2.客户端
1.创建一个Socket对象,指定服务器端的地址和端口;
private String host = "localhost";
private int port = 8000;
private Socket socket;
……
socket = new Socket(host, port);
这里作为客户端,它的端口是由操作系统随机产生的。
2.Socket类提供了getInputStream()方法和getOutputStream |