本文介绍一下再Java中Socket的实现。
目录
一、需要掌握
二、程序源码
三、运行演示
一、介绍
Java Socket实现实时接收TCP消息需要客户端和服务端两个部分。
二、JavaSocket源码示例
客户端后台部分代码
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 1234)) {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
while (true) {
String message = in.readLine();
if (message == null) {
break;
}
System.out.println("Received message: " + message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端后台部分代码
public class Server {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(1234)) {
System.out.println("Server started");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println("Welcome to the server");
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
while (true) {
String message = in.readLine();
if (message == null) {
break;
}
System.out.println("Received message: " + message);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码演示了客户端连接到指定的服务端Socket,接收到服务端发送的消息,并在控制台输出。
三、WebSocket源码示例
前端范例
var socket = new WebSocket("ws://localhost:1234");
socket.onmessage = function(event) {
console.log("Received message: " + event.data);
};
以上代码演示了使用WebSocket连接到指定的服务器,接收到消息时在控制台输出。
后端范例
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/echo")
public class WebSocketServer {
@OnMessage
public void onMessage(String message, Session session) {
try {
session.getBasicRemote().sendText("Received message: " + message);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(1234)) {
System.out.println("Server started");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println("Welcome to the server");
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
while (true) {
String message = in.readLine();
if (message == null) {
break;
}
System.out.println("Received message: " + message);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码演示了使用WebSocket实现服务端接收消息,并将接收到的消息原样发送回客户端。