Android通過Socket(TCP/IP)與PC通訊

來源:互聯網
上載者:User

這個簡單的例子將示範應用Java實現用戶端與伺服器端傳輸檔案的方法。

伺服器端原始碼:
import java.net.*;<br />import java.io.*;<br />public class FileServer {<br /> public static void main (String [] args ) throwsIOException {<br /> // create socket<br /> ServerSocket servsock = new ServerSocket(13267);<br /> while (true) {<br /> System.out.println("Waiting...");<br /> Socket sock = servsock.accept();<br /> System.out.println("Accepted connection : " + sock);<br /> // sendfile<br /> File myFile = new File ("source.pdf");<br /> byte [] mybytearray = new byte [(int)myFile.length()];<br /> FileInputStream fis = new FileInputStream(myFile);<br /> BufferedInputStream bis = new BufferedInputStream(fis);<br /> bis.read(mybytearray,0,mybytearray.length);<br /> OutputStream os = sock.getOutputStream();<br /> System.out.println("Sending...");<br /> os.write(mybytearray,0,mybytearray.length);<br /> os.flush();<br /> sock.close();<br /> }<br /> }<br />}


用戶端原始碼:
import java.net.*;<br />import java.io.*;<br />public class FileClient{<br /> public static void main (String [] args ) throws IOException {<br /> int filesize=6022386; // filesize temporary hardcoded<br /> long start = System.currentTimeMillis();<br /> int bytesRead;<br /> int current = 0;<br /> // localhost for testing<br /> Socket sock = new Socket("127.0.0.1",13267);<br /> System.out.println("Connecting..."); </p><p> // receive file<br /> byte [] mybytearray = new byte [filesize];<br /> InputStream is = sock.getInputStream();<br /> FileOutputStream fos = new FileOutputStream("source-copy.pdf");<br /> BufferedOutputStream bos = new BufferedOutputStream(fos);<br /> bytesRead = is.read(mybytearray,0,mybytearray.length);<br /> current = bytesRead;<br /> // thanks to A. Cádiz for the bug fix<br /> do {<br /> bytesRead =<br /> is.read(mybytearray, current, (mybytearray.length-current));<br /> if(bytesRead >= 0) current += bytesRead;<br /> } while(bytesRead > -1); </p><p> bos.write(mybytearray, 0 , current);<br /> bos.flush();<br /> long end = System.currentTimeMillis();<br /> System.out.println(end-start);<br /> bos.close();<br /> sock.close();<br /> }<br />} 

相關文章

聯繫我們

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