套接字(Socket)是网络通信的基本构建块,它允许不同计算机上的应用程序通过互联网进行通信。套接字分为两种主要类型:流套接字(用于TCP通信)和数据报套接字(用于UDP通信)。TCP是一种面向连接的协议,提供可靠的数据传输;而UDP是一种无连接协议,传输速度更快但不保证数据的可靠性。
import java.io.*;
import java.net.*;
public class JavaClient {
public static void main(String[] args) {
String hostName = "127.0.0.1";
int portNumber = 12345;
try (Socket socket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("Type message to send: ");
String userInput = stdIn.readLine();
out.println(userInput);
System.out.println("Server response: " + 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);
}
}
}
import socket
host = '127.0.0.1'
port = 12345
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((host, port))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print(f"Received message: {data.decode()}")
conn.sendall(data)
import socket
host = '127.0.0.1'
port = 12345
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((host, port))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print(f"Received message: {data.decode()}")
response = "Hello from Python server!"
conn.sendall(response.encode())
import java.io.*;
import java.net.*;
public class JavaClient {
public static void main(String[] args) {
String hostName = "127.0.0.1";
int portNumber = 12345;
try (Socket socket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("Type message to send: ");
String userInput = stdIn.readLine();
out.println(userInput);
System.out.println("Server response: " + 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);
}
}
}
通过上述代码和解释,你应该能够实现Java客户端与Python服务器之间的双向通信。如果遇到具体问题,请检查网络连接、端口设置和编码一致性。
领取专属 10元无门槛券
手把手带您无忧上云