Socket
類(lèi)表示一個(gè)TCP客戶端套接字。
以下代碼顯示如何創(chuàng)建TCP客戶端套接字:
// Create Socket for 192.168.1.2 at port 1234 Socket socket = new Socket("192.168.1.2", 1234);
以下代碼顯示如何創(chuàng)建未綁定的客戶端套接字,綁定它并連接它。
Socket socket = new Socket(); socket.bind(new InetSocketAddress("localhost", 1234)); socket.connect(new InetSocketAddress("localhost", 1234));
在連接Socket對(duì)象之后,我們可以分別使用getInputStream()和getOutputStream()方法使用其輸入和輸出流。
以下代碼顯示了基于TCP套接字的Echo客戶端。
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class Main { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 12900); System.out.println("Started client socket at " + socket.getLocalSocketAddress()); BufferedReader socketReader = new BufferedReader(new InputStreamReader( socket.getInputStream())); BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())); BufferedReader consoleReader = new BufferedReader( new InputStreamReader(System.in)); String promptMsg = "Please enter a message (Bye to quit):"; String outMsg = null; System.out.print(promptMsg); while ((outMsg = consoleReader.readLine()) != null) { if (outMsg.equalsIgnoreCase("bye")) { break; } // Add a new line to the message to the server, // because the server reads one line at a time. socketWriter.write(outMsg); socketWriter.write("\n"); socketWriter.flush(); // Read and display the message from the server String inMsg = socketReader.readLine(); System.out.println("Server: " + inMsg); System.out.println(); // Print a blank line System.out.print(promptMsg); } socket.close(); } }
更多建議: