第一个是我的客户端,第二个是服务器端,为什么客户端不能通过socket向服务器发送第二轮消息?当你在控制台里放东西的时候,服务器会通过socket响应,然后把消息发送回客户端。但是当我第二次在控制台里放东西的时候,消息就不能再发送到服务器了,请告诉我为什么。谢谢
package client;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
static Socket sock ;
static InputStreamReader IR;
public static void main(String[] args) throws IOException,
InterruptedException
{
Client client = new Client();
sock = new Socket("localhost", 1112);
IR = new InputStreamReader(sock.getInputStream());
client.run();
}
public void run() throws IOException, InterruptedException
{
while(true)
{
PrintStream PS = new PrintStream(sock.getOutputStream());
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
int age = sc.nextInt();
PS.println(age);
if(age == 0)
{
break;
}
System.out.println("here");
BufferedReader BR = new BufferedReader(IR);
String MSG = BR.readLine();
System.out.println("client: server has received "+MSG);
Thread.sleep(1000);
}
sock.close();
}
}
package server;
import java.io.*;
import java.net.*;
public class Server {
static ServerSocket serverSocket;
public static void main(String[] args) throws IOException,
InterruptedException {
Server server = new Server();
serverSocket = new ServerSocket(1112);
server.run();
}
public void run() throws IOException, InterruptedException
{
while(true)
{
//ServerSocket serverSocket = new ServerSocket(1112);
Socket socket = serverSocket.accept();
InputStreamReader IR = new
InputStreamReader(socket.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String msg = BR.readLine();
System.out.println("server: I have received "+msg);
Thread.sleep(2000);
if(msg != null)
{
PrintStream PS = new
PrintStream(socket.getOutputStream());
PS.println(msg);
}else
{
break;
}
}
serverSocket.close();
}
}
1条答案
按热度按时间ax6ht2ek1#
因此,当客户机套接字尝试连接到服务器套接字时,它会被放到服务器端的队列中。然后
.accept()
方法将请求从队列中移除,并“连接”两个套接字。所以,在你的代码里,
客户端请求连接,
服务器接受它,
客户端向服务器发送年龄,
服务器读取并发回,
客户端向服务器发送另一个age
服务器从不做任何事情
问题发生在服务器端的步骤4之后。它称之为
.accept()
方法,但没有客户端请求连接,因此.accept()
只需等待,直到它得到一个请求连接的套接字(称为阻塞方法)。你可以通过移动
Socket socket = serverSocket.accept()
在外面while(true)
服务器上的循环