javase socket
时间: 2024-12-26 13:26:10 浏览: 7
### Java SE中的Socket编程
Java SE提供了强大的网络通信功能,其中`java.net.Socket`类和`java.net.ServerSocket`类用于实现TCP/IP协议下的客户端和服务端之间的连接[^1]。
#### 创建服务器端套接字
服务端通过创建`ServerSocket`对象监听特定端口等待来自客户端的请求:
```java
import java.io.*;
import java.net.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
int port = 7;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("EchoServer started on port " + port);
while(true){
Socket clientSocket = serverSocket.accept();
handleClient(clientSocket);
}
}
}
private static void handleClient(Socket socket) throws IOException{
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (".".equals(inputLine))
break;
out.println(inputLine);
}
} finally {
if(out!=null)out.close();
if(in!=null)in.close();
socket.close();
}
}
}
```
此代码片段展示了如何设置一个简单的回声服务器,它接收并返回任何发送给它的消息直到收到`.`字符为止。
#### 客户端套接字建立连接
为了与上述的服务端交互,在客户端可以利用`Socket`来发起连接尝试,并读取响应数据流:
```java
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
String hostName = "localhost";
int portNumber = 7;
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in))
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
```
这段程序实现了向指定主机名和端口号发出连接请求的功能,并能够持续输入字符串至远程服务器直至手动终止进程。
阅读全文