Java中进行网络编程主要涉及到使用Java的Socket和ServerSocket类。以下是一个简单的TCP客户端和服务器的例子:
TCP服务器
java复制代码
import java.io.*; | |
import java.net.*; | |
public class TCPServer { | |
public static void main(String[] args) throws IOException { | |
int port = 8000; | |
try ( | |
ServerSocket serverSocket = new ServerSocket(port); | |
Socket clientSocket = serverSocket.accept(); // accept the client connection | |
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); | |
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); | |
) { | |
String inputLine; | |
while ((inputLine = in.readLine()) != null) { // read from the client | |
out.println(inputLine); // send back the data to the client | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
TCP客户端
java复制代码
import java.io.*; | |
import java.net.*; | |
public class TCPClient { | |
public static void main(String[] args) throws IOException { | |
String hostName = "localhost"; // or 127.0.0.1 for IPv4 loopback address | |
int port = 8000; | |
try ( | |
Socket echoSocket = new Socket(hostName, port); | |
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) { // read from stdin and send to the server | |
out.println(userInput); // send the data to the server | |
System.out.println("Echo from the server: " + in.readLine()); // read from the server and display on console | |
} | |
} 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); | |
} | |
} | |
} |
以上是一个简单的回声服务器和客户端的例子,服务器接收客户端发送的消息,然后将其原样返回。这只是网络编程的冰山一角,实际应用中可能需要处理更复杂的情况,例如并发连接、错误处理、数据加密等。