关于流与网络编程的问题,求高手,讲原理.... 20
importjava.net.*;importjava.io.*;importjava.util.*;classTCPTest{publicstaticvoidmain(...
import java.net.*;
import java.io.*;
import java.util.*;
class TCPTest {
public static void main(String[] args) throws Exception
{
new Thread(){ //启动服务端
public void run(){
try{
Server.play();
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
Thread.sleep(5000); //暂停5秒钟
new Thread(){
public void run(){
try{
Client.play();
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
}
}
class Client//客户端
{
public static void play() throws Exception{
Socket socket = new Socket("127.0.0.1",8888);
BufferedInputStream is =new BufferedInputStream(socket.getInputStream());
OutputStream os = socket.getOutputStream();
os.write("链接开启\nhello".getBytes());
byte[] b =new byte[1024];
int len;
while((len=is.read(b))!=-1){
System.out.println(new String(Arrays.copyOf(b,len)));
}
}
}
class Server//服务端
{
public static void play() throws Exception{
ServerSocket server = new ServerSocket(8888);
while(true){
Socket socket=server.accept();
OutputStream os = socket.getOutputStream();
DataInputStream dis = new DataInputStream(socket.getInputStream());
/*byte[] b = new byte[1024];
int len = dis.read(b);
System.out.println(new String(Arrays.copyOf(b,len)));
*/
System.out.println(dis.readUTF()); //发生堵塞
//若使用多行注释中的代码,就不会发生堵塞
System.out.println("客户端IP:"+socket.getInetAddress().getHostName());
System.out.println("客户端端口:"+socket.getPort());
os.write("bye\n链接结束!!".getBytes());
}
}
}
求解释,为什么使用dis.readUTF(),会发生堵塞 展开
import java.io.*;
import java.util.*;
class TCPTest {
public static void main(String[] args) throws Exception
{
new Thread(){ //启动服务端
public void run(){
try{
Server.play();
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
Thread.sleep(5000); //暂停5秒钟
new Thread(){
public void run(){
try{
Client.play();
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
}
}
class Client//客户端
{
public static void play() throws Exception{
Socket socket = new Socket("127.0.0.1",8888);
BufferedInputStream is =new BufferedInputStream(socket.getInputStream());
OutputStream os = socket.getOutputStream();
os.write("链接开启\nhello".getBytes());
byte[] b =new byte[1024];
int len;
while((len=is.read(b))!=-1){
System.out.println(new String(Arrays.copyOf(b,len)));
}
}
}
class Server//服务端
{
public static void play() throws Exception{
ServerSocket server = new ServerSocket(8888);
while(true){
Socket socket=server.accept();
OutputStream os = socket.getOutputStream();
DataInputStream dis = new DataInputStream(socket.getInputStream());
/*byte[] b = new byte[1024];
int len = dis.read(b);
System.out.println(new String(Arrays.copyOf(b,len)));
*/
System.out.println(dis.readUTF()); //发生堵塞
//若使用多行注释中的代码,就不会发生堵塞
System.out.println("客户端IP:"+socket.getInetAddress().getHostName());
System.out.println("客户端端口:"+socket.getPort());
os.write("bye\n链接结束!!".getBytes());
}
}
}
求解释,为什么使用dis.readUTF(),会发生堵塞 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询