網路程式設計基礎-socket基礎

風的王子發表於2015-05-20

server端

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(30000);
        while(true) {
            Socket s = ss.accept();
            PrintStream ps = new PrintStream(s.getOutputStream());
            ps.print("你收到了伺服器的資訊");
            ps.close();
            s.close();
        }
    }
}

client 端

public class Client {
    public static void main(String[] args) throws UnknownHostException,
            IOException {

        // Socket socket = new Socket("127.0.0.1", 30000);
        // socket.setSoTimeout(1000);

        // 建立一個無連線的socket,然後在連線
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress("127.0.0.1",30000), 10000);

        BufferedReader br = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
        String line = br.readLine();
        System.out.println("來自伺服器資訊:" + line);

        br.close();
        socket.close();

    }
}

用netstat -a 檢視埠
TCP 127.0.0.1:30000 xxx:xxxxxx TIME_WAIT

重新撿回失去的東西

相關文章