服务器端的工作非常简单,建立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 }
View Code

相关文章:

  • 2021-10-13
  • 2022-12-23
  • 2022-02-07
  • 2022-02-21
  • 2022-12-23
  • 2021-05-15
  • 2021-05-06
  • 2021-12-05
猜你喜欢
  • 2021-10-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
  • 2021-07-10
  • 2021-06-11
相关资源
相似解决方案