具体的发包与拆包的协议可以自己定义:
我定义:包头第一个字节为1时则为接收文件为0则为接收字符
服务器:
private static void writefile(DataOutputStream dos, FileInputStream fis) {
byte[] bytes=new byte[2];//先发包头
int length;
bytes[0]=1;
bytes[1]=5;
try {
dos.write(bytes);//发给客户端
} catch (IOException e) {
e.printStackTrace();
System.out.println("发送包头失败");
}
try{
byte[] bytes1=new byte[1024];//发送包体数据
while((length=fis.read(bytes1, 0,bytes1.length))!=-1){
dos.write(bytes1,0,bytes1.length);
dos.flush();
}
}catch(Exception e){
e.printStackTrace();
System.out.println("发送文件包体数据失败");
}
}
private static void writestring(DataOutputStream dos) {
// TODO Auto-generated method stub
String string="sending";
byte[] bytes=new byte[2];//同理发送字符串的包头
bytes[0]=0;
bytes[1]=5;
try {
dos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
System.out.println("发送包头失败");
}
try {
byte[] bytes1=new byte[1024];//发送字符串的包体数据
bytes1=string.getBytes();
dos.write(bytes1);
} catch (IOException e1) {
e1.printStackTrace();
System.out.println("发送字符包体数据失败");
}
}
}
客户端:
try{
s=new Socket("192.168.1.106",45);
Log.d(TAG, "run:2222222222222");
is=s.getInputStream();
dis=new DataInputStream(is);
new Thread(){
@Override
public void run(){
super.run();
try{
dis = new DataInputStream(s.getInputStream());
Log.d(TAG, "33333333333333");
byte[] bytes=new byte[2];
dis.read(bytes);
if(bytes[0]==0){
int a=bytes[1];
byte[] bytes1=new byte[a];
dis.readFully(bytes1);
String ssss=new String(bytes1);
Message msg=new Message();
msg.what=2;
msg.obj=ssss;
revhandler.sendMessage(msg);
}
else {
{
File file=new File("/storage/emulated/0/1/c.jpg");
Log.d(TAG,"run:2.55555555555555555555555");
fos=new FileOutputStream(file);
Log.d(TAG,"run:333333333333333333333");
inputByte = new byte[30];//接收数据
Message msg=new Message();
msg.what=0;
revhandler.sendMessage(msg);
Log.d(TAG,"run:44444444444444");
while((length = dis.read(inputByte, 0, inputByte.length)) != -1) {
Log.d(TAG,"44444444");
fos.write(inputByte,0,inputByte.length);
fos.flush();
}
msg = new Message();
msg.what=1;
revhandler.sendMessage(msg);
if(fos != null)
fos.close();
if(dis != null)
dis.close();
s.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
运行结果:
服务器:
![V1LEZDBZ07VQ482$02HO%R.png
客户端: