[Java]利用Scoket发送各类文件-实例代码-长连接-极简代码-TCP协议

来源:互联网 发布:gps转百度地图坐标 js 编辑:程序博客网 时间:2024/06/04 18:59

关于TCP的知识:

http://blog.csdn.net/shenpibaipao/article/details/70176038


客户端:

import java.io.File;import java.io.FileInputStream;import java.io.OutputStream;import java.net.Socket;public class FileTransTest {public static void main(String[] args) throws Exception{//1.建立SocketSocket socket=new Socket("127.0.0.1",12121);//2.文件输入FileInputStream fr=new FileInputStream(new File("E:/test/t1/a.jpg"));OutputStream out=socket.getOutputStream();byte[] buf=new byte[1024];//缓存对象int len=0;//3.向socket输入数据while((len=fr.read(buf))!=-1){out.write(buf,0,len);}socket.shutdownOutput();//不会关闭Socketif(socket.isClosed())System.out.println("关闭");else{System.out.println("未关闭");//控制台输出"未关闭"。这样你就可以继续使用这个长连接 : )}}}



服务器:

import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class FileTransTestServer {public static void main(String[] args) throws Exception{//1.绑定端口ServerSocket serverSocket=new ServerSocket(12121);serverSocket.setSoTimeout(2000);//超时2秒Socket socket=serverSocket.accept();//套接//2.获取输入流InputStream in = socket.getInputStream();  FileOutputStream fw=new FileOutputStream(new File("E:/test/t2/a.jpg"));byte[] buf=new byte[1024];//缓存int len=0;//3.写文件while((len=in.read(buf))!=-1){fw.write(buf,0,len);//写入从0起,长度为1024的byte[]}}}



原创粉丝点击