首页 > 代码库 > Android Socket简单测试
Android Socket简单测试
这里是将pc作为server,设备作为客户端。
Server端代码:
public static final String SERVERIP = "192.168.0.2";
public static final int SERVERPORT = 51706;
public void run()
{
try
{
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);// 创建一个监听51706端口的serversocket
while (true)
{
Socket client = serverSocket.accept();//得到客户端的socket
System.out.println("S: Receiving...");
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("S: Received: ‘" + str + "‘");
}
catch (Exception e)
{
System.out.println("S: Error");
e.printStackTrace();
}
finally
{
client.close();
System.out.println("S: Done.");
}
}
}
catch (Exception e)
{
System.out.println("S: Error");
e.printStackTrace();
}
}
Client段代码:注意:这段代码不能直接放在主程序中,我们可以将代码放在线程中,通过handler去刷新UI。
InetAddress serverAddr = null;
try
{
serverAddr = InetAddress.getByName("192.168.0.2");
}
catch (UnknownHostException e2)
{
// TODO Auto-generated catch block
e2.printStackTrace();
}// TCPServer.SERVERIP
Log.d("TCP", "C: Connecting...");
Socket socket = null;
try
{
socket = new Socket(serverAddr, 51706);//尝试连接服务器
}
catch (IOException e1)
{
// 连接服务器失败会抛出IOException , 这里需要自己处理
e1.printStackTrace();
}
String message = "AndroidRes,Where is my Pig (Android)?";
try
{
Log.d("TCP", "C: Sending: ‘" + message + "‘");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(message);//发送数据
}
catch (Exception e)
{
Log.e("TCP", "S: Error", e);
}
finally
{
try
{
socket.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
还有两点需要注意:
1、我在测试时pc和设备是处在同一局域网内的,但是网段却不同,所以一直处于连接失败的状态,解决的办法就是通过修改pc段的网关,使其处于同一个网段中就可以了。
2、服务器关闭的话上面的创建socket连接有可能会导致卡机,抛出ANR的情况,因为即使我们设置的超时时间再短,也会过很久才抛出IO异常,这时候我们可以使用isa做一下处理
private Socket client;
private int timeout = 5000;
private InetSocketAddress isa;
client = new Socket();
isa = new InetSocketAddress(ip, port);
client.connect(isa, timeout);
如果出现端口被占用的情况可以做一下处理:
打开命令行,输入 netstat -ano
找到占用端口的进程id,通过管理器杀掉