本帖最后由 李敬 于 2012-8-20 05:55 编辑
网络编程知识点中的代码
import java.io.*;
import java.net.*;
class TextClient
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.1.254",10006);
BufferedReader bufr =
new BufferedReader(new FileReader("IPDemo.java"));
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
String line = null;
while((line=bufr.readLine())!=null)//A---在这里如果没有了数据会阻塞
{
out.println(line);
}
s.shutdownOutput();//B---所以要关闭客户端的输出流。相当于给流中加入一个结束标记-1.
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = bufIn.readLine();
System.out.println(str);
bufr.close();
s.close();
}
}
class TextServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10006);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"....connected");
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(new FileWriter("server.txt"),true);
String line = null;
while((line=bufIn.readLine())!=null)//C---这里也会阻塞
{
out.println(line);
}
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
pw.println("上传成功");
out.close();
s.close();
ss.close();
}
}
我的问题就是
socket这种方式中的readLine没有数据时会阻塞
我们之前写的本地的文本复制程序中,readLine没有数据不会阻塞.
这有什么区别吗?
|