我在客户端-服务器应用程序中遇到问题。客户端向服务器发送图片,服务器以回复消息进行响应。
这是我的服务器代码:
public class Server
{
public static void main(String[] args) throws Exception
{
String response="response";
ServerSocket socket = new ServerSocket(3333);
while (true)
{
Socket clientSocket = socket.accept();
DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
FileOutputStream fout = new FileOutputStream("output.jpg");
int i;
while ( (i = dis.read()) > -1)
fout.write(i);
DataOutputStream outToClient= new DataOutputStream(clientSocket.getOutputStream());
outToClient.writeBytes(response);
fout.flush();
fout.close();
dis.close();
outToClient.close();
clientSocket.close();
}
}
}
客户:
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub
String sentence;
int i;
FileInputStream fis = new FileInputStream ("pathphoto.jpg");
Socket sock = new Socket ("hostname",3333);
DataOutputStream os = new DataOutputStream(sock.getOutputStream());
System.out.println("Sending....");
while ((i = fis.read()) > -1)
os.write(i);
BufferedReader inFromServer= new BufferedReader(new InputStreamReader(sock.getInputStream()));
sentence=inFromServer.readLine();
System.out.println("FROM SERVER: " + sentence);
fis.close();
os.close();
sock.close();
}
}
问题是客户端没有收到来自服务器的响应,我认为是这样的:
BufferedReader inFromServer= new BufferedReader(new InputStreamReader(sock.getInputStream()));
sentence=inFromServer.readLine();
因为没有它们,服务器会发送响应。
关于如何解决它的任何建议?