在Java主方法中使用Socket编程,你需要遵循以下步骤:
import java.io.*;
import java.net.*;
int port = 12345; // 你可以选择任何可用的端口号
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
accept()
方法接受客户端的连接请求:Socket socket = serverSocket.accept();
System.out.println("Client connected");
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String message;
while ((message = bufferedReader.readLine()) != null) {
System.out.println("Received from client: " + message);
}
PrintWriter printWriter = new PrintWriter(outputStream, true);
printWriter.println("Hello from server!");
bufferedReader.close();
printWriter.close();
socket.close();
serverSocket.close();
将以上代码整合到Java主方法中,完整的示例如下:
import java.io.*;
import java.net.*;
public class SocketServer {
public static void main(String[] args) {
int port = 12345; // 你可以选择任何可用的端口号
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
try {
Socket socket = serverSocket.accept();
System.out.println("Client connected");
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream, true);
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String message;
while ((message = bufferedReader.readLine()) != null) {
System.out.println("Received from client: " + message);
}
printWriter.println("Hello from server!");
bufferedReader.close();
printWriter.close();
socket.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
serverSocket.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
运行此程序后,服务器将监听端口12345。当客户端连接到该端口时,服务器将接收客户端发送的消息,并向客户端发送一条响应消息。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。