Android学习笔记(七)之Android socket通信-解决中文乱码
目前想让手机客户端和服务器保持长连接故选择socket进行通信
首先是新建一个socket服务器端
[java]
/**
* Main.java
* 版权所有(C) 2012
* 创建:cuiran 2012-09-14 08:56:16
*/
package com.wpndemo.socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* TODO
* @author cuiran
* @version TODO
*/
public class Main {
private static final int PORT = 8090;
private List<Socket> mList = new ArrayList<Socket>();
private ServerSocket server = null;
private ExecutorService mExecutorService = null; //thread pool
public static final String bm="utf-8"; //全局定义,以适应系统其他部分
public static void main(String[] args) {
new Main();
}
public Main() {
try {
server = new ServerSocket(PORT);
mExecutorService = Executors.newCachedThreadPool(); //create a thread pool
System.out.print("server start ...");
Socket client = null;
while(true) {
client = server.accept();
mList.add(client);
mExecutorService.execute(new Service(client)); //start a new thread to handle the connection
}
}catch (Exception e) {
e.printStackTrace();
}
}
class Service implements Runnable {
private Socket socket;
private BufferedReader in = null;
private String msg = "";
public Service(Socket socket) {
this.socket = socket;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream(),bm));
msg = "user" +this.socket.getInetAddress() + "come toal:"
+mList.size();
this.sendmsg();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(true) {
if((msg = in.readLine())!= null) {
if(msg.equals("exit")) {
System.out.println("ssssssss");
mList.remove(socket);
in.close();
msg = "user:" + socket.getInetAddress()
&nbs
补充:移动开发 , Android ,