java做伺服器,android做用戶端,實現資料轉送

來源:互聯網
上載者:User

許久未動筆,有個小項目開始動工。

需要用一台windows電腦做伺服器,在android端與其進行資料交換,實現一些業務。

簡單起見,用java寫這個伺服器,以前沒做過,試試水。很簡單的代碼,純粹找思路。

伺服器端代碼:

package com.test;import java.io.IOException;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class MyServer {public static void main(String[] args) {try {ServerSocket server = new ServerSocket(8888);while (true) {System.out.println("execute 1\n");Socket client = server.accept();System.out.println("execute 2\n");OutputStream out = client.getOutputStream();System.out.println("execute 3\n");String msg = "hello android";out.write(msg.getBytes());System.out.println("execute 4\n");client.close();}} catch (IOException e) {e.printStackTrace();}}}

用了吉利的數字8888做連接埠,等android端串連上來,發送一句話給android。

 

android端代碼:

package com.teat;import java.io.IOException;import java.io.InputStream;import java.net.Socket;import java.net.UnknownHostException;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class TestSocketActivity extends Activity {private TextView myTextView;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);myTextView = (TextView) findViewById(R.id.textView1);try {myTextView.setText("0");Socket socket = new Socket("192.168.1.100", 8888);myTextView.setText("1");InputStream in = socket.getInputStream();byte[] buffer = new byte[in.available()];myTextView.setText("2");in.read(buffer);myTextView.setText("3");String msg = new String(buffer);myTextView.setText(msg);} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}

方便起見,ip地址是寫死的,通過dos視窗下的ipconfig指令查看自己電腦的本地ip,然後把下面這行代碼裡的ip修改成你電腦的ip就可以正常通訊了。

Socket socket = new Socket("192.168.1.100", 8888);

如果正常通訊的話會顯示伺服器發來的“hello android”;

代碼下載:http://download.csdn.net/detail/jason0539/7011951

 

作者:jason0539

微博:http://weibo.com/2553717707

部落格:http://blog.csdn.net/jason0539(轉載請說明出處)

聯繫我們

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