您的位置:首页 > 其它

socket文件传输

2016-08-09 14:05 169 查看
今天来写一下socket文件传输.

之前公司项目用到了局域网内的通信,前一篇文章讲了一下upd的广播,这一篇准备简单的说说socket通信问题.

socket通信需要两个条件:ip与port.

首先需要知道主机的ip,然后知道主机的port,才能够进行通信.

好了,不多说了(关键是了解的太少)直接上代码:

服务端

ServerSocket ss;
Socket s = null;
ss = new ServerSocket(port);
s = ss.accept();


定义一个服务器对象ss,定义一个套接字s.创建一个服务器new ServerSocket.通过阻塞方法accept等待客户端的接入.

客户端

Socket socket = null;
socket = new Socket(ip, port);


定义一个套接字socket,接入到服务器new Socket.

服务端与客户端的整体结构大概就是这样.

接下来上具体代码.

服务端:

ServerSocket ss;
Socket s = null;
DataInputStream fis;
DataOutputStream ps;
private void sendFile(File fi) {
try {
ss = new ServerSocket(Params.sendAndAccept_Port);
while (true) {
// 选择进行传输的文件
if (!fi.exists()) {
break;
}
System.out.println("文件长度:" + (int) fi.length());
s = ss.accept();
System.out.println("建立socket链接");
try {
// 先将文件变成input流,再转成output流发送出去
fis = new DataInputStream(new BufferedInputStream(new FileInputStream(fi)));
ps = new DataOutputStream(s.getOutputStream());
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();
int bufferSize = 1024;
byte[] buf = new byte[bufferSize];=
int read = 0;
while ((read = fis.read(buf)) > -1) {
ps.write(buf, 0, read);
}
ps.flush();
// 注意关闭socket链接哦,不然客户端会等待server的数据过来,直到socket超时,导致数据不完整。
fis.close();
s.close();
System.out.println("文件传输完成");
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}


客户端:

Soket s=null;
InputStream is;
DataOutputStream out = null;
DataInputStream in= null;
private void receive(){
try {
s = new Socket(ip, port);
in=new DataInputStream(new BufferedInputStream(s.getInputStream()));
String savePath = Environment.getExternalStorageDirectory().toString()+"/";
int bufferSize = 1024;
byte[] buf = new byte[bufferSize];
long len=0;
savePath += inputStream.readUTF();
out = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();
System.out.println("文件的长度为:" + len + "\n");
System.out.println("开始接收文件!" + "\n");
int read = 0;
while ((read = inputStream.read(buf))>-1) {
out.write(buf, 0, read);
}
System.out.println("接收完成,文件存为" + savePath + "\n");
Message msg=new Message();
msg.what=1;
handler.sendMessage(msg);
out.close();
} catch (Exception e) {
System.out.println("接收消息错误" + "\n");
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}

Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what==1) {
ToastUtil.Show.toast.show(Client1Activity.this, "接收完成", Toast.LENGTH_LONG);
}
}
};


好了,差不多就这么多了.

这次没有源码,直接复制上边的就可以用了.

最后,结束的时候记得调用close.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  socket