由于我不知道的原因,我无法在Android(4.2)和我的电脑之间建立连接。相同的代码适用于我的同事...
服务器代码如下(相关部分):
private static List<Socket> socketList = Collections.synchronizedList(new ArrayList<Socket>());
private ExecutorService exec;
private ServerSocket server;
public static void main(String[] args) {
new AndroidServer();
}
public AndroidServer() {
try {
server = new ServerSocket(80);
exec = Executors.newCachedThreadPool();
Socket client = null;
while (true) {
client = server.accept();
System.out.println("hello")
socketList.add(client);
exec.execute(new ChatTask(client));
}
} catch (IOException e) {
e.printStackTrace();
}
}
客户端代码(在Android手机上)看起来像这样(有点乱,对不起):
try {
String IP_ADDRESS = "123.123.123.123";
socket = new Socket(IP_ADDRESS, 80);
exec.execute(new Sender(socket));
userId = socket.getInetAddress() + ":" + socket.getLocalPort();
println("[" + userId + "] is connected with Android Server");
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
String mstr = br.readLine();
if (mstr != null) {
text1.setText(mstr); //text1 is a text field in the Android view
} else {
text1.setText("");
}
out.close();
br.close();
socket.close();
}
static class Sender implements Runnable{
private Socket socket;
public Sender(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
String msg;
while (true) {
msg = br.readLine();
if (msg.length() == 0)
{
print(socket.getLocalPort()+":>");
} else {
pw.println(msg);
continue;
}
[some code skipped]
}
pw.close();
br.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Android源码的AndroidManifest.xml如下所示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.testSocket"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".TestSocket"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>