java吧 关注:1,225,844贴子:12,682,535
  • 1回复贴,共1

请教一个Java ServerSocket问题

取消只看楼主收藏回复

最近在研究Java遇到一个问题,如下面代码,我接收客户端的请求信息,为什么客户端关闭之后才接收到客户端发送过来的数据?求大神讲解一下,谢谢!
package com;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket serverSocket;
private Socket socket;
private final static int PORT = 8000;
public Server()
{
}
public static void main(String[] args)
{
try
{
//1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口
ServerSocket serverSocket=new ServerSocket(8080);
Socket socket=null;
//记录客户端的数量
int count=0;
System.out.println("***服务器即将启动,等待客户端的连接***");
//循环监听等待客户端的连接
while(true){
//调用accept()方法开始监听,等待客户端的连接
socket=serverSocket.accept();
//创建一个新的线程
ServerThread serverThread=new ServerThread(socket);
//启动线程
serverThread.start();
count++;//统计客户端的数量
System.out.println("客户端的数量:"+count);
InetAddress address=socket.getInetAddress();
System.out.println("当前客户端的IP:"+address.getHostAddress());
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
class ServerThread extends Thread
{
private Socket socket;
public ServerThread(Socket _socket)
{
socket = _socket;
}
public void run()
{
InputStream is=null;
BufferedReader br=null;
OutputStream os=null;
PrintWriter pw=null;
try {
//获取输入流,并读取客户端信息
is = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String info=br.readLine();
System.out.println("我是服务器,客户端说:"+info);
socket.shutdownInput();//关闭输入流
//获取输出流,响应客户端的请求
os = socket.getOutputStream();
pw = new PrintWriter(os);
pw.write("欢迎您!");
pw.flush();//调用flush()方法将缓冲输出
} catch (IOException e)
{
e.printStackTrace();
}
finally{
//关闭资源
try {
System.out.println("socket close");
if(pw!=null)
pw.close();
if(os!=null)
os.close();
if(br!=null)
br.close();
if(is!=null)
is.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


1楼2017-06-09 11:06回复
    11111111111111111


    2楼2017-06-09 11:12
    回复