今天學習了一下java如何實現socket通信,感覺難點反而是在io上,因為java對socket封裝已經很完善了。
今天代碼花了整個晚上調試,主要原因是io的flush問題和命令行下如何運行具有package的類,不過最后問題基本都解決了,把代碼貼出來供大家參考
server
public class TcpServer { public static void main(String[] args) throws Exception { ServerSocket server = new ServerSocket(9091); try { Socket client = server.accept(); try { BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream())); boolean flag = true; int count = 1; while (flag) { System.out.println(客戶端要開始發騷了,這是第 + count + 次!); count++; String line = input.readLine(); System.out.println(客戶端說: + line); if (line.equals(exit)) { flag = false; System.out.println(客戶端不想玩了!); } else { System.out.println(客戶端說: + line); } } } finally { client.close(); } } finally { server.close(); } } }
client
public class TcpClient { public static void main(String[] args) throws Exception { Socket client = new Socket(127.0.0.1, 9091); try { PrintWriter output = new PrintWriter(client.getOutputStream(), true); Scanner cin = new Scanner(System.in); String words; while (cin.hasNext()) { words = cin.nextLine(); output.println(words); System.out.println(寫出了數據: + words); } cin.close(); } finally { client.close(); } } }
