这两天在学习socket网络编程方面的知识,本来再java上运行的测试的好好的,但到了android上,客户端老是连接不上,在网上看了许多资料,总结了手机客户端连接PC服务端的条件:
1、
P
C 和手机要在同一个网络内,比如无线路由器,手机用wifi连接路由,pc也连接路由,cmd命令查看下PC的ip地址,请确保你的IP是PC的IP,把你PC防火墙关掉,socket连接最好用
2、android4.0版本以上的,网络连接代码不能写在主线程中,必须新建一个线程。
3、
在Manifest.xml文件当中,需要对互联网的访问进行授权
<uses-permission android:name="android.permission.INTERNET"/>
PC服务端:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream in = null;
DataOutputStream out = null;
try {
serverSocket = new ServerSocket(12345);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while(true){
socket = serverSocket.accept();
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
out.writeUTF(in.readUTF()+"\n儿子乖");
out.close();
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
android客户端:
package com.example.socketdemo;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static TextView textView;
public static Button button;
public static Handler handler = new Handler();
public static String text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textview);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
thread.start();
}
});
textView.setText(text);
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Socket socket;
DataInputStream in;
DataOutputStream out;
try {
socket = new Socket("192.168.1.104", 12345);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("爸爸");
text = in.readUTF();
textView.post(new Runnable() {
@Override
public void run() {
textView.setText(text);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"与服务器断开连接", Toast.LENGTH_LONG).show();
}
}
});
}