下面是有一个服务器接受多个客户端连接并响应的代码。服务器能够接收客户端的消息,但客户端没有接收服务器消息。我在服务器上使用了多线程概念。我还观察到,除了标有#### 的行之外,没有任何效果(甚至是 println 语句)。可能是那个客户端被阻止了..有什么想法吗?服务器代码:public static void main(String argv[]) throws Exception {
ServerSocket welcomeSocket = new ServerSocket(10000);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
Thread t = new Thread(new acceptconnection(connectionSocket));
t.start();}}
class acceptconnection implements Runnable{
BufferedReader inFromClient,inn;
DataOutputStream ds;
Socket clientsocket;
//constructor
acceptconnection (Socket socket) throws IOException{
this.clientsocket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
ds = new DataOutputStream(clientsocket.getOutputStream());
public void run (){
try {
String clientSentence, inp;
while(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("from client" + clientSentence);
ds.writeBytes("hi from server");**// THIS DOES NOT WORK**
}
}
Client code:
public static void main(String argv[]) throws Exception
{
Socket clientSocket;
while(true)
{
// clientSock
clientSocket = new Socket("localhost", 10000);
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter something:");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');// THIS WORKS - thats why server receives it
**####** modifiedSentence = inFromServer.readLine();**// THIS DOES NOT WORK -client unable to receive**
System.out.println("FROM SERVER: " + modifiedSentence + "remote sock add: "+ clientSocket.getRemoteSocketAddress());