JAVA高级进阶12网络通信
在Java中,网络通信通常涉及到Java Socket编程。以下是一个简单的Java Socket客户端和服务器端的例子。
服务器端代码:
import java.io.*;
import java.net.*;
public class SimpleServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Waiting for clients...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected!");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message;
while ((message = in.readLine()) != null) {
System.out.println("Client says: " + message);
out.println("Server response: " + message);
if (message.equals("bye"))
break;
}
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}
客户端代码:
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
String userInputLine;
System.out.println("Type 'bye' to exit the chat.");
while ((userInputLine = userInput.readLine()) != null) {
out.println(userInputLine);
System.out.println("Client says: " + userInputLine);
if (userInputLine.equals("bye"))
break;
System.out.println("Server response: " + in.readLine());
}
userInput.close();
in.close();
out.close();
socket.close();
}
}
在这个例子中,服务器端创建了一个ServerSocket
在端口8888上监听,然后接受来自客户端的连接。服务器端和客户端通过PrintWriter
和BufferedReader
来发送和接收字符串信息。当信息为"bye"时,双方断开连接。这个例子展示了基本的Socket编程,但在实际应用中,你可能需要处理更复杂的网络通信和异常处理。
评论已关闭