服务器端的工作非常简单,建立socket.监听,代码如下:
package com.hdc.socket; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class JavaServer { 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客户端的编码:
因为操作线程不能在主线程,故:
1 package com.hdc.sockettestclient; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.widget.TextView; 6 7 public class MainActivity extends Activity { 8 private TextView myTextView; 9 10 @Override 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.activity_main); 14 15 myTextView = (TextView) findViewById(R.id.textView1); 16 17 new YunTheard(myTextView).start(); 18 19 } 20 }
package com.hdc.sockettestclient; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.UnknownHostException; import android.widget.TextView; public class YunTheard extends Thread { private TextView myTextView; public YunTheard(TextView myTextView) { super(); this.myTextView = myTextView; } @Override public void run() { try { myTextView.setText("0"); Socket socket = new Socket("172.17.1.41", 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(); } } }
通信成功后客户端会显示来自服务端的hello,android
时间: 2024-12-06 06:22:03