许久未动笔,有个小项目开始动工。
需要用一台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(转载请说明出处)