Java学习笔记-----从套接字中读写数据

来源:互联网 发布:linux搭建multicraft 编辑:程序博客网 时间:2024/06/05 13:52

向套接字中读写流的方法:

经过我试验,发现,有俩种方法可行:

1.      使用DataInputStream 从套接字流中读取数据 

同时必须配合DataOutputStream向套接字流中写入数据。

 

       实例:

       :DataInputStream dis  =new DataInputStream(s.getInputqStream());

        String cont                     =dis.readUTF();

              System.out.println(“客户端发来:”+cont);

 

DataOutputStream   dos =new DataOutputStream(s.getOutStream());

String info =”你好啊”;

dos.writeUTF(info);

 

dos.flush();

 

 

2.      第二种情况是,使用PrintWriter 向套接字流中写入数据,用BufferedReader读取。

实例:

PrintWriter pw=newPrintWriter(s.getOutputStream(),true);

String response=br2.readLine();

                      // 把从控制台接收的信息,写入套接字

pw.println(response);

 

InputStreamReaderisr=new InputStreamReader(s.getInputStream());

               BufferedReader br=newBufferedReader(isr);

String res=      br2.readLine();

                             System.out.println("服务器说:"+res);

0 0
原创粉丝点击