一、Socket Programming是什么
Socket Programming(套接字编程)是指使用Socket API进行网络编程。在Java中,Socket可以用来通过TCP/IP协议进行数据交换,可以实现不同机器之间的数据通信。
Socket编程通过创建Socket对象来开启一个端口,端口号是从1到65535之间的整数。一台机器可以同时开启多个端口,不同的端口用来提供不同的服务。
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class SocketServer { public static void main(String[] args) throws IOException { int portNumber = 8080; ServerSocket serverSocket = new ServerSocket(portNumber); while (true) { Socket clientSocket = serverSocket.accept(); // 开启线程处理客户端请求 new RequestHandler(clientSocket).start(); } } }
二、实现Tcp Server服务端
要实现一个Tcp Server服务端,需要创建一个ServerSocket对象,调用accept()方法等待客户端请求,当有客户端请求时,会返回一个Socket对象,通过该对象即可与客户端通信。
开启一个ServerSocket对象,设置端口号,使用accept()方法等待客户端请求:
ServerSocket serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept();
获取客户端请求后,可以使用输入流读取客户端发送的数据,使用输出流向客户端发送响应数据:
InputStream inputStream = clientSocket.getInputStream(); OutputStream outputStream = clientSocket.getOutputStream();
完整的Tcp Server服务端代码示例:
import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class TcpServer { public static void main(String[] args) throws IOException { int portNumber = 8080; ServerSocket serverSocket = new ServerSocket(portNumber); while (true) { Socket clientSocket = serverSocket.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String inputLine; while ((inputLine = in.readLine()) != null) { out.println(inputLine); } } } }
三、实现Tcp Client客户端
要实现一个Tcp Client客户端,需要创建一个Socket对象,连接指定的服务器地址和端口号,然后使用输入输出流向服务器发送请求和接收响应。
创建一个Socket对象,设置服务器地址和端口号,向服务器发送请求,并读取响应:
Socket socket = new Socket(serverAddress, portNumber); OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream();
完整的Tcp Client客户端代码示例:
import java.io.*; import java.net.Socket; public class TcpClient { public static void main(String[] args) throws IOException { String serverAddress = "localhost"; int portNumber = 8080; Socket socket = new Socket(serverAddress, portNumber); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.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()); } } }
四、使用UDP协议进行数据传输
使用UDP(User Datagram Protocol)协议可以实现不需要建立连接,直接进行数据传输的网络通信。相比于TCP,UDP更轻便,但无法保证数据的可靠性和顺序。
使用UDP协议创建一个DatagramSocket对象,然后创建一个DatagramPacket对象,该对象包含发送或接收的数据和目标地址和端口号。通过send()方法向指定地址发送数据包,使用receive()方法接收数据包。
完整的UDP Server服务端代码示例:
import java.io.IOException; import java.net.*; public class UdpServer { public static void main(String[] args) throws IOException { int portNumber = 8080; DatagramSocket serverSocket = new DatagramSocket(portNumber); byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); while (true) { serverSocket.receive(receivePacket); String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); System.out.println("Received message: " + message); InetAddress address = receivePacket.getAddress(); int port = receivePacket.getPort(); byte[] sendData = message.toUpperCase().getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port); serverSocket.send(sendPacket); } } }
完整的UDP Client客户端代码示例:
import java.io.IOException; import java.net.*; public class UdpClient { public static void main(String[] args) throws IOException { String serverAddress = "localhost"; int portNumber = 8080; DatagramSocket clientSocket = new DatagramSocket(); InetAddress address = InetAddress.getByName(serverAddress); byte[] sendData = "Hello, UDP!".getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, portNumber); clientSocket.send(sendPacket); byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); System.out.println("Received message: " + message); } }
五、总结
本文详细介绍了使用Java编写Socket程序实现网络通信的方法,包括Tcp Server服务端,Tcp Client客户端,以及UDP协议的实现方式。希望读者能够通过本文加深对Socket编程的理解,实践中灵活运用。