JAVASE学习笔记第24天

Pic上传图片

/**

需求:上传图片

为了保证数据的正确传输,采用TCP协议

*/

import java.io.*;

import java.net.*;

 

//客户端

/**

1,建立服务

2,读取客户端已经有的图片数据

3,通过socket输出流将数据发给服务端

4,读取服务端反馈的信息

5,关闭资源

*/

class PicCilent

{

       publicstatic void main(String[] args)throws Exception

       {

 

              if(args.length!=1)

              {

                     System.out.println("请选择一个jpg格式的文件");

                     return;

              }

 

              Filefile = new File(args[0]);

              if(!(file.exists()&& file.isFile()))

              {

                     System.out.println("该文件有问题,要么不存在,要么不是文件");

                     return;

              }

 

              if(!(file.getName().endWith(".jpg")))

              {

                     System.out.println("图片的格式有错误,请重新选择");

                     return;

              }

 

              if(file.length()>1024*1024*5)

              {

                     System.out.println("不要搞鬼~\(≧▽≦)/~啦啦啦");

                     return;

              }

 

              //1,建立socket服务端点

              Sockets = new Socket("169.254.138.44",10004);

 

              //2,读取客户端已有的图片数据

              FileInputStreamfis=new FileInputStream("F:\\1.jpg");

 

              //3通过Socket输出流将数据发给服务端

              OutputStreamout = s.getOutputStream();

             

              //一下代码的意思就是建立一个缓冲区,把文件的数据首先都读到缓冲区中,然后写到socket输出流中

              byte[]buf=new byte[1024];

              intlen=0;

              while((len=fis.read(buf))!=-1)

              {

                     out.write(buf,0,len);

              }

             

              //告诉服务端数据已经传完了

              s.shutdownOutput();        

 

              //4,读取服务端的反馈信息

              InputStreamin = s.getInputStream();

              byte[]bufIn =new byte[1024];

              intnum=in.read(bufIn);

              System.out.println(newString(bufIn,0,num));

 

              //5,关闭资源

              fis.close();

              s.close();                    

       }

}

 

//服务端

/**

(这个很重要啊)

 因为accept方法以及read方法都是阻塞式的方法,这就导致当我们多个客户端无法同时访问服务端

 

 那么为了可以让多个客户端能够同时并发访问服务端,

 就可以将每个客户端封装到一个单独的线程中,这样就可以同时处理多个客户端的请求了。

 

 如何定义线程呢?

 只要明确每个客户端在服务端要执行的代码就可以了,将改代码封装到线程中

*/

 

class PicThread implements Runnable

{

       //封装一个客户端

       privateSocket s;

       PicThread(Sockets)

       {

              this.s=s;

       }

       publicvoid run()

       {

              Stringip=s.getInetAddress().getHostAddress();

              intcount =1;

 

              try

              {

                     System.out.println(ip+"......connect");

 

                     //3,通过socket读取流,接收数据(源)

                     InputStreamin = s.getInputStream();

                    

                     //为了防止文件的覆盖

                     Filefile=new File(ip+"("+(count)+")"+".jpg");

                    

                  while(file.exists())

                            file=newFile(ip+"("+(count++)+")"+".jpg");

                     //4,(目的)

                     FileOutputStreamfos =new FileOutputStream(file);

 

                     byte[]buf = new byte[1024];

                     intlen=0;

                     while((len=in.read(buf))!=-1)

                     {

                            fos.write(buf,0,len);

                     }

 

                     //5,给客户端的提示

                     OutputStreamout = s.getOutputStream();

                     out.write("上传成功".getBytes());

 

                     //6,关闭资源

                     fos.close();

                     s.close();                           

              }

              catch(Exception e)

              {

                     thrownew RuntimeException(ip+"上传失败");

              }            

      

       }

}

 

class PicServer

{

       publicstatic void main(String[] args)throws Exception

       {

              //1,建立服务端的端点

              ServerSocketss =new ServerSocket(10004);

             

              while(true)

              {

                     //2,接收客户端的端点

                     Sockets=ss.accept();

 

                     newThread(new PicThread(s)).start();

              }

              //ss.close();//如果服务端只是上传一次的话

       }

}

 

客户端并发登录

/**

需求:

客户端通过键盘录入用户名,服务端对这个用户名进行校验。

 

如果该用户名存在,在服务端系显示xxx,已登录

并在客户端显示xxx,欢迎光临

 

如果该用户不存在,在服务端显示xxx,尝试登录

并在客户端显示xxx,该用户不存在

 

最多登录三次。

*/

 

import java.io.*;

import java.net.*;

 

//客户端

class LoginCilent

{

       publicstatic void main(String[] args)throws Exception

       {

              Sockets =new Socket("localhost",10004);

              //读键盘

              BufferedReaderbufr=

                     newBufferedReader(new InputStreamReader(System.in));

 

              //写入到socket流中

              PrintWriterout=

                     newPrintWriter(s.getOutputStream(),true);

 

              //读服务端

              BufferedReaderbufIn=

                     newBufferedReader(new InputStreamReader(s.getInputStream()));

 

              for(intx=0;x<3;x++)

              {

                     //读键盘的

                     Stringline=bufr.readLine();

                     if(line==null)

                            break;

                     out.println(line);

                    

                     //读服务端

                     Stringinfo=bufIn.readLine();

                     System.out.println("info:"+info);

                     if(info.contains("欢迎"))

                            break;                 

              }

 

              bufr.close();

              s.close();

       }

}

 

//线程

class UserThread implements Runnable

{

       privateSocket s;

       UserThread(Sockets)

       {

              this.s=s;

       }

       publicvoid run()

       {

              Stringip=s.getInetAddress().getHostAddress();

              System.out.println(ip+".....connext");

              try

              {

                     for(intx=0;x<3;x++)

                     {

                            //读入键盘中的数据

                            BufferedReaderbufIn=

                                   newBufferedReader(new InputStreamReader(s.getInputStream()));

 

                            Stringname=bufIn.readLine();

                            if(name==null)

                                   break;

                           

                            //相当于读数据库中的数据

                            BufferedReaderbufr=new BufferedReader(new FileReader("userinfo.txt"));

                           

                            PrintWriterout =new PrintWriter(s.getOutputStream());

 

                            Stringline=null;

                            //根据循环后的结果判断

                            booleanflag=false;

                            while((line=bufr.readLine())!=null)

                            {

                                   //找到了

                                   if(line.equals(name))

                                   {

                                          flag=true;

                                          break;

                                   }

                            }

 

                            if(flag)

                            {

                                   System.out.println(name+",已经登录");

                                   out.println(name+",欢迎光临");

                                   break;

                            }

                            else

                            {

                                   System.out.println(name+",尝试登录");

                                   out.println(name+",用户名不存在");                              

                            }                                 

                     }

                     s.close();

              }

              catch(Exception e)

              {

                     thrownew RuntimeException(ip+"校验失败");

              }

 

       }

}

 

//服务端

class LoginServer

{

       publicstatic void main(String[] args)throws Exception

       {

              ServerSocketss=new ServerSocket(10004);

 

              while(true)

              {

                     Sockets =ss.accept();

 

                     newThread(new UserThread(s)).start();

              }

       }

}

 

 

 

 

 

 

B/S

 

/*

演示客户端和服务端

 

1,客户端:浏览器

    服务端:自定义

import java.net.*;

import java.io.*;

class Demo3

{

       publicstatic void main(String[] args)throws Exception

       {

              ServerSocketss =new ServerSocket(11000);

 

              Sockets =ss.accept();

              System.out.println(s.getInetAddress().getHostAddress());

             

              PrintWriterout=new PrintWriter(s.getOutputStream(),true);

 

              out.println("客户端你好");

 

              s.close();

              ss.close();

       }

}

 

 

2,客户端:浏览器

  服务端:tomcat服务器。

 

  玩服务器想要明确窗口。

 

 

import java.net.*;

import java.io.*;

class Demo3

{

       publicstatic void main(String[] args)throws Exception

       {

              ServerSocketss =new ServerSocket(11000);

 

              Sockets =ss.accept();

              System.out.println(s.getInetAddress().getHostAddress());

             

              InputStreamin =s.getInputStream();

 

              byte[]buf=new byte[1024];

              intlen =in.read(buf);

              System.out.println(newString(buf,0,len));

             

              PrintWriterout=new PrintWriter(s.getOutputStream(),true);

 

              out.println("客户端你好");

 

              s.close();

              ss.close();

       }

}

 

GET / HTTP/1.1

Host: 127.0.0.1:11000

User-Agent: Mozilla/5.0 (Windows NT 6.1;rv:32.0) Gecko/20100101 Firefox/32.0

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,;q=0.8

Accept-Language:zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: keep-alive

 

3,客户端:自定义

     服务端:tomcat

*/

 

import java.io.*;

import java.net.*;

 

class Demo3

{

       publicstatic void main(String[] args)

       {

              Sockets =new Socket("localhost",8080);

             

              PrintWriterout=new PrintWriter(s.getOutputStream(),true);

 

              out.println("GET/ HTTP/1.1");

              out.println("Accept:*/*");

              out.println("Accept-Language:zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");

              out.println("Host:127.0.0.1:11000");

              out.println("Connection:keep-alive");

 

              //一定要写空行

              out.println();

              out.println();

 

              BufferedReaderbufr =

                     newBufferedReader(new InputStream(s.getInputStream()));

 

              Stringline=null;

              while((line=bufr.readLine())!=null)

              {

                     System.out.println(line);  

              }

              s.close();             

       }

}

 

URl-URLConnection

/*

String getFile()

         获取此 URL 的文件名。

 String getHost()

         获取此 URL 的主机名(如果适用)。

 String getPath()

         获取此 URL 的路径部分。

 intgetPort()

         获取此 URL 的端口号。

 String getProtocol()

         获取此 URL 的协议名称。

 String getQuery()

          获取此 URL 的查询部分。

               

返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。        

public URLConnection openConnection()

                             throws IOException

 

*/

 

import java.net.*;

 

class URLDemo

{

       publicstatic void main(String[] args)

       {

               URL url = newURL("http://127.0.0.1:8080/myweb/demo.html");

             

              //这个在应用层,有了它就不用建立socket服务了,

              //socket是在传输层。

               URLConnection conn=url.openConnection();

               System.out.println(conn);

 

               byte[] buf=new byte[1024];

               int len=in.read(buf);

             

               System.out.println(new String(buf,0,len));

 

       }     

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值