Java Socket编程系列(一)开发一次性会话的Server和Client
关于什么是Socket:
A socket is one end-point of a two-way communication link between two programs running on the network.
Socket是网络上运行的2个程序之间通信链接的终点。说白了就是代表一条通信链路的两端。
Socket classes are used to represent the connection between a client program and a server program.
Socket类用来代表客户端程序和服务器端程序的连接。
The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively
Java中的java.net包提供了Socket和ServerSocket类分别实现连接的客户端和服务端。
Java中如何编写?
服务器端:
package com.dylan.socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器
*
* @author xusucheng
* @create 2017-12-21
**/
public class Server {
public static final int PORT = 8858;//监听的端口号
public static void main(String[] args) throws Exception {
System.out.println("Server started! Listening...");
ServerSocket serverSocket = new ServerSocket(PORT);
Socket server = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out = new PrintWriter(server.getOutputStream());
String readLine = in.readLine();
if (readLine != null) {
System.out.println("Receive message from Client: " + readLine);
out.println("Roger!");
}
out.close();
in.close();
server.close();
serverSocket.close();
}
}
客户端:
package com.dylan.socket;
import java.io.*;
import java.net.Socket;
/**
* 客户端
*
* @author xusucheng
* @create 2017-12-20
**/
public class Client {
public static final String HOST = "127.0.0.1";//服务器地址
public static final int PORT = 8858;//服务器端口号
public static void main(String[] args) throws Exception{
Socket client = new Socket(HOST,PORT);
//创建输入流
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//创建输出流
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
//向服务器程序发送信息
out.println("Hello Server! This is Client! ");
//接收来自服务器程序的响应
String readLine=in.readLine();
if(readLine!=null){
System.out.println("Receive message from Server: "+readLine);
}
//关闭链接
out.close();
in.close();
client.close();
}
}
启动
服务器端
Server started! Listening...
Receive message from Client: Hello Server! This is Client!
客户端:
Receive message from Server: Roger!