Java實現簡單的socket通信


  今天學習了一下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();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM