2 u012965960 u012965960 于 2014.08.25 16:39 提问

Android Socket服务器线程问题

急!急!急!我是搞java得由于公司有个项目没有android人手,让我做了一个app。马上就要交付测试了,现在遇到这样的问题:启动Android Socket服务端时报错说不让在主线程启动,找了一下相关资料说将线程启动到后台可是不知道怎么改,这是我的代码。

ServerSocket server;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Button bt_action = (Button) findViewById(R.id.bt_action);

    bt_action.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                ServerSocket server = new ServerSocket();
                while (true) {
                    // 未连通前线程阻塞,连通后开启一个socket通道线程后继续监听9999端口
                    Socket socket = server.accept();
                    System.out.println(socket.getInetAddress()
                            .getHostAddress() + "连接进入");
                    new SocketThread(socket).start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    });
}

// 一个服务器端口中监听多个客服端通道线程
class SocketThread extends Thread {
    // 所有通道写入流的集合
    private final List<PrintWriter> list = new ArrayList<PrintWriter>();

    private BufferedReader bufferedReader;
    private PrintWriter printWriter;
    InputStream in = null;

    public SocketThread(Socket socket) throws IOException {
        this.bufferedReader = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
        this.printWriter = new PrintWriter(socket.getOutputStream());
        this.in = socket.getInputStream();
        list.add(printWriter);
    }

    @Override
    public void run() {
        String string = null;
        while (true) {
            try {
                // 服务器在通道中读到的信息回显给客服端
                string = bufferedReader.readLine();
                System.out.println("客服端信息:" + string);
                for (PrintWriter printWriter : list) {
                    // printWriter.write("服务器显示:" + string + "\r\n");
                    printWriter.flush();
                }
            } catch (IOException e) {
            }
        }
    }
}

2个回答

HDinger
HDinger   2015.04.02 19:56

new Thread(new Runnable() {
@Override
public void run() {
ServerSocket server = new ServerSocket();
while (true) {
// 未连通前线程阻塞,连通后开启一个socket通道线程后继续监听9999端口
Socket socket = server.accept();
System.out.println(socket.getInetAddress()
.getHostAddress() + "连接进入");
new SocketThread(socket).start();
}
}
}.start();
这样就好了

wuxin782515516
wuxin782515516   2016.06.29 10:59

这就是所谓的长连接吗?能实现服务器改过数据 客户端立即能收到数据吗?

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!