Socket分包传输
不分包
public static String getSocketString(String json,String ip,int port){
String info = null;
StringBuffer returnInfo = new StringBuffer();
PrintWriter pw=null;
OutputStream os =null;
BufferedReader br =null;
InputStream is=null;
Socket socket=null;
try {
socket = new Socket(ip,port);
String s=lengjs(json.length());
String str=s+json;
log.debug("发送socket数据包"+str);
os = socket.getOutputStream();
pw = new PrintWriter(os);
pw.write(str);
Thread.sleep(1000);
pw.flush();
socket.shutdownOutput();
is = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while((info = br.readLine())!=null){
returnInfo.append(info);
log.debug("客户端返回成功:"+info);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(br!=null)
br.close();
if(is!=null)
is.close();
if(os!=null)
os.close();
if(pw!=null)
pw.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnInfo.toString();
}
分包
public static String getSocketString1(String json,String ip,int port){
String info = null;
StringBuffer returnInfo = new StringBuffer();
PrintWriter pw=null;
OutputStream os =null;
BufferedReader br =null;
InputStream is=null;
Socket socket=null;
try {
socket = new Socket(ip,port);
socket.setSoTimeout(10* 1000);
byte[] byteDatas = json.getBytes("utf-8");
os = socket.getOutputStream();
int index = 0;
while (index < len)
{
byte[] buf;
if ((len -index) / 1024 > 0) {
buf = new byte[1024];
System.arraycopy(byteDatas, index, buf, 0, 1024);
}
else
{
buf = new byte[len - index];
System.arraycopy(byteDatas, index, buf, 0, len - index);
}
os.write(buf);
index = index + 1024;
}
is = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while((info = br.readLine())!=null){
returnInfo.append(info);
log.debug("客户端返回成功:"+info);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(br!=null)
br.close();
if(is!=null)
is.close();
if(os!=null)
os.close();
if(pw!=null)
pw.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnInfo.toString();
}