以下是一个基本的Java socket编程案例:
服务端代码:
import java.net.*;
import java.io.*;public class Server {public static void main(String[] args) throws IOException {ServerSocket serverSocket = null;try {serverSocket = new ServerSocket(8080);} catch (IOException e) {System.err.println("Could not listen on port: 8080.");System.exit(1);}Socket clientSocket = null;try {System.out.println("Waiting for connection.....");clientSocket = serverSocket.accept();System.out.println("Connection successful");} catch (IOException e) {System.err.println("Accept failed.");System.exit(1);}PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));String inputLine;while ((inputLine = in.readLine()) != null) {System.out.println("Server: " + inputLine);out.println(inputLine);if (inputLine.equals("Bye."))break;}out.close();in.close();clientSocket.close();serverSocket.close();}
}
客户端代码:
import java.net.*;
import java.io.*;public class Client {public static void main(String[] args) throws IOException {Socket socket = null;PrintWriter out = null;BufferedReader in = null;try {socket = new Socket("localhost", 8080);out = new PrintWriter(socket.getOutputStream(), true);in = new BufferedReader(new InputStreamReader(socket.getInputStream()));} catch (UnknownHostException e) {System.err.println("Don't know about host: localhost.");System.exit(1);} catch (IOException e) {System.err.println("Couldn't get I/O for the connection to: localhost.");System.exit(1);}BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));String userInput;while ((userInput = stdIn.readLine()) != null) {out.println(userInput);System.out.println("Client: " + userInput);if (userInput.equals("Bye."))break;System.out.println("Server: " + in.readLine());}out.close();in.close();stdIn.close();socket.close();}
}
这个案例实现了一个简单的客户端和服务端之间的通信,客户端向服务端发送一条消息,服务端将其打印后返回给客户端。如果客户端发送了 "Bye.",则结束通信。