java-TCP用戶端和服務端初始

來源:互聯網
上載者:User

想著之後一定會用到eclipse和資料庫的串連,這客服端和服務端是必學的,如今最近也才開始慢慢學,跟著視頻學習。

import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class ClientDemo2 {public static void main(String[] args) throws UnknownHostException, IOException {Socket so=new Socket("192.168.241.1",10002);//擷取socket流中的輸出資料流OutputStream out=so.getOutputStream();//使用輸出資料流將指定的輸入寫出去out.write("慢慢來".getBytes());//讀取服務端返回的資料,使用socket讀取流InputStream in=so.getInputStream();byte[] buf=new byte[1024];int len=in.read(buf);String text=new String(buf,0,len);System.out.println(text);so.close();}}
這個是用戶端的執行個體代碼,使用了socket,需要指定的IP地址以及指定連接埠。然後使用到了流操作。最後有 讀取服務端返回的資料,使用socket讀取流。


import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class ServerDemo2 {public static void main(String[] args) throws IOException {ServerSocket ss=new ServerSocket(10002);Socket s=ss.accept(); //擷取用戶端對象String ip=s.getInetAddress().getHostAddress();InputStream in=s.getInputStream(); //IO操作流規律byte[] buf=new byte[1024];int len=in.read(buf);String text=new String(buf, 0, len);System.out.println(ip+"Serve:"+text);//使用用戶端socket對象的輸出資料流給用戶端返回資料OutputStream out=s.getOutputStream();out.write("收到".getBytes());s.close();ss.close();}}
然後這裡是服務端的案例,Server這個單詞很明顯的是吧。主要是要擷取用戶端對象accept,就可以得到IP地址和資料流,然後再用流操作得到文本資料。

還是需要繼續理解。理解過程。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.