在Java中,你可以使用多种方法进行网络通信。以下是一些基本的方法:
java.net.Socket和java.net.ServerSocket类进行TCP通信。客户端示例:
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8080);
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
writer.println("Hello, Server!");
socket.close();
}
}
服务器端示例:
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String message = reader.readLine();
System.out.println("Client says: " + message);
socket.close();
serverSocket.close();
}
}
java.net.DatagramSocket和java.net.DatagramPacket类进行UDP通信。客户端示例:
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
byte[] buffer = "Hello, Server!".getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 8080);
socket.send(packet);
socket.close();
}
}
服务器端示例:
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8080);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("Client says: " + message);
socket.close();
}
}
这些示例展示了如何在Java中使用命令行进行基本的网络通信。你可以根据自己的需求修改这些示例,以实现更复杂的功能。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。