自學篇-網路編程TCP(九)

來源:互聯網
上載者:User



import java.net.*; import java.io.*;

class TcpClient {
    public static void main(String[] args) throws Exception{
        //1.建立Socket服務
        Socket sk = new Socket("192.168.0.105",10003);
        //2.運用Socket服務的getOutputStream()方法寫資料
        OutputStream out = sk.getOutputStream();
        out.write("wo yao xue bian cheng".getBytes());
        //3.關閉資源
        sk.close();
    }
}

class TcpServer{
    public static void main(String[] args) throws Exception{
        //1.建立Socket 服務並監聽連接埠
        ServerSocket ss = new ServerSocket(10003);
        //2.通過accept()方法擷取用戶端對象
        Socket s = ss.accept();
        String ip = s.getInetAddress().getHostAddress();
        System.out.print("ip="+ip);
        //3.使用用戶端對象擷取資料
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        System.out.print(new String(buf,0,len));
        //4.關閉資源
        s.close();
        ss.close();
    }

}


用戶端與服務端資料互動

import java.io.*;
import java.net.*;

class  TcpClient{
    public static void main(String[] args) throws Exception{
        Socket sk = new Socket("10.56.192.176",10005);
        OutputStream out = sk.getOutputStream();
        out.write("wo yoa xue biancheng".getBytes());
        
        InputStream in = sk.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        System.out.print(new String(buf,0,len));

        sk.close();
    }
}

class TcpServer {
    public static void main(String[] args)throws Exception{
        ServerSocket ss = new ServerSocket(10005);
        Socket s = ss.accept();
        String ip = s.getInetAddress().getHostAddress();
        System.out.print("ip=" + ip);
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        System.out.print(new String(buf,0,len));
        
        OutputStream out = s.getOutputStream();
        out.write("哥們收到".getBytes());

        s.close();
        ss.close();
    }
}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.