使用最原始的java.net.ServerSocket和java.net.Socket进行socket通信。实现的效果为:客户端向服务端发送消息、服务端向客户端发送消息、保留统计客户端的信息列表、剔除已经断开的客户端等。
本文所有代码均可在https://gitee.com/songxinqiang/JavaSocketDemo查看。
服务端
接受用户输入端口并且启动服务器的入口类,还需要完成接受用户输入发送给客户端
public class Main {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入服务器端口(默认8080):");
Integer port =8080;
try {
port = Integer.parseInt(reader.readLine());
} catch (Exception e1) {
e1.printStackTrace();
}
SocketServer server = new SocketServer(port);
while (true) {
try {
String line = reader.readLine();
if (line.equals("exit")) {
System.exit(0);
break;
}
server.sendMessage(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务器类需要完成启动ServerSocket接受客户端连接、保留客户端信息、清除已经断开的客户端信息、对外暴露向客户端发送消息的接口
使用到了定时器,代码需要java8环境,日志记录为slf4j接口
public class SocketServer extends TimerTask {
private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);
ServerSocket serverSocket;
private List<SocketClientHandler> clients = new ArrayList<>();
/**
* 开启监听,接受链接
*/
public SocketServer(Integer port) {
// 清理客户端
new Timer(true).schedule(this, 1000, 1000);
try {
serverSocket = new ServerSocket(port);
logger.info("服务端已启动,等待客户端连接..");
new Thread(() -> {
while (!serverSocket.isClosed()) {
try {
Socket socket = serverSocket.accept();
String clientIP = socket.getInetAddress()
.getHostAddress();
logger.info("client:{}", clientIP);
SocketClientHandler handler = new SocketClientHandler(socket);
handler.start();
clients.add(handler);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* {@inheritDoc}<br>
* 用于清理已经断开的客户端
*
*/
@Override
public void run() {
Iterator<SocketClientHandler> it = clients.iterator();
while (it.hasNext()) {
SocketClientHandler handler = it.next();
if (!handler.isAlive()) {
it.remove();
}
}
}
/**
* 往客户端发送消息
*
* @param msg
* 消息
*/
public void sendMessage(String msg) {
logger.info("send:{}", msg);
clients.stream()
.forEach(client -> client.sendMessage(msg));
}
}
客户端信息处理为单独的线程,保存客户端的socket对象,接受客户端消息并进行处理(这里只是打印),同时实际完成向客户端发送消息
public class SocketClientHandler extends Thread {
private static final Logger logger = LoggerFactory.getLogger(SocketClientHandler.class);
Socket client;
String ip;
BufferedReader reader;
PrintWriter writer;
public SocketClientHandler(Socket socket) {
this.ip = socket.getInetAddress()
.getHostAddress();
try {
this.client = socket;
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
logger.error("init socket client error,{}", e.getMessage());
}
}
/**
* {@inheritDoc}<br>
*
*/
@Override
public void run() {
while (!client.isClosed()) {
try {
String msg = reader.readLine();
if (msg == null) {
break;
}
receiveMessage(msg);
} catch (IOException e) {
logger.info(e.getMessage());
break;
}
}
}
/**
* 收到消息之后的处理
*
* @param msg
* 收到的消息
*/
public void receiveMessage(String msg) {
logger.info("from:{},receive:{}", ip, msg);
}
/**
* 发送消息
*
* @param msg
* 发送的消息
*/
public void sendMessage(String msg) {
logger.info("to:{},send:{}", ip, msg);
writer.println(msg);
}
}
代码通过Main类启动之后要求用户输入服务器端口,然后开始接受客户端连接,打印客户端ip地址、发送过来的信息、接受用户输入并向所有客户端进行发送。
客户端
客户端的启动类完成向用户询问服务器地址和端口的操作,然后向服务端发起连接,接受用户输入,并发送到服务端
public class SocketClient {
private static final Logger logger = LoggerFactory.getLogger(SocketClient.class);
/**
* 启动客户端,连接服务器
*/
public SocketClient() {
try {
// 从控制台输入
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入服务器地址:");
String host = reader.readLine();
System.out.print("请输入服务器端口:");
Integer port = Integer.parseInt(reader.readLine());
Socket socket = new Socket(host, port);
logger.info("连接:{}:{}", host, port);
// 开启多线程接收信息,并解析
ClientHandler thread = new ClientHandler(socket);
thread.start();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
while (!socket.isClosed()) {
String line = reader.readLine();
if (line == null || line.isEmpty()) {
continue;
}
logger.info("读取:{}", line);
// 发送消息
writer.println(line);
writer.flush();
}
} catch (Exception e) {
logger.error("服务器异常,{}", e.getMessage());
}
}
public static void main(String[] args) {
new SocketClient();
}
}
客户端信息处理
由于客户端的启动类需要完成用户输入的收集,所以接受服务端消息的操作由单独的线程进行,用于对服务器端发送过来的消息进行处理
public class ClientHandler extends Thread {
private static final Logger logger = LoggerFactory.getLogger(ClientHandler.class);
private Socket socket;
BufferedReader reader;
public ClientHandler(Socket socket) {
this.socket = socket;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* {@inheritDoc}<br>
* 接收消息并打印,在收到的消息为{@code null}或者空字符串时退出
*
*/
@Override
public void run() {
while (!socket.isClosed()) {
try {
String msg = reader.readLine();
if (msg == null) {
break;
}
receiveMessage(msg);
} catch (IOException e) {
logger.info(e.getMessage());
break;
}
}
}
/**
* 对服务器发送消息进行处理
*
* @param msg
* 消息内容
*/
public void receiveMessage(String msg) {
logger.info("收到:{}", msg);
}
}
maven打包
为了将程序打包为一个可执行jar,同时包含日志记录依赖,使用maven打包,关键代码为(以client为例,服务器端类似,详见git)
<properties>
<assembly-plugin.version>3.1.0</assembly-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 构建一个单文件可执行jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>${assembly-plugin.version}</version>
<configuration>
<descriptors>
<descriptor>src/assembly/assembly.xml</descriptor>
</descriptors>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>cn.songxinqiang.demo.socket.SocketClient</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
运行效果
程序使用maven打包之后运行效果为