/**
* 连接服务器
* @param serverIp 服务器ip
* @param port 端口
* @param msg 消息
* @return 服务端返回数据
*/
public static String getSocketResult(String serverIp,int port,String msg){
Socket socket=null;
String result=null;
InputStream in=null;
OutputStream outputStream=null;
try {
//套接字连接服务器
InetAddress severAddress=InetAddress.getByName(serverIp);
socket=new Socket(severAddress, port);
outputStream=socket.getOutputStream();
outputStream.write(msg.getBytes("gbk"));
outputStream.flush();
in=socket.getInputStream();
int count=0;
byte[] inDatas = null;
while (count == 0) {
count = in.available();
}
inDatas = new byte[count];
in.read(inDatas);
in.close();
return new String(inDatas, "gb2312");
} catch (Exception e) {
// TODO: handle exception
}finally{
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
android客户端利用套接字访问网络调试助手实现一问一答工具类
最新推荐文章于 2024-03-27 22:57:21 发布