基於TCP協議的客戶端 此客戶端能用於下一篇博客的單線程服務器和多線程服務器
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; public class JabberClient { public static void main(String[] args) throws IOException { new KeHuJi(); } } class KeHuJi { BufferedReader in = null; PrintWriter out = null; public String name = null; class JieShou extends TimerTask//每隔一段時間就檢查本地這個端口是否有新的消息發送過來 { public void run() { String string = null; try { string = in.readLine(); if (string != null) { System.out.println(string); } } catch (Exception e) { // TODO: handle exception } } } public KeHuJi() throws IOException { InetAddress addr = InetAddress.getLocalHost(); Socket socket = null; String ipString = null; Scanner scanner = new Scanner(System.in); System.out.println("請輸入服務器的ip"); ipString = scanner.next(); socket = new Socket(ipString, 8089);//創建一個客戶對象並與服務器相連 端口是8089,此時服務器會收到一個連接請求 System.out.println("請輸入的你的名字"); name = scanner.next(); scanner.close(); try { System.out.println("連接成功"); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); Timer timer = new Timer(); JieShou jieShou = new JieShou(); timer.schedule(jieShou, 10, 200);//每隔200毫秒就接收一次服務器發來的消息 while (true)//發送消息 { Scanner in1 = new Scanner(System.in); out.println(name + ": " + in1.next()); } } catch (Exception e) { } finally { socket.close(); } } }