繁体   English   中英

如何获得服务器对客户端消息的响应

[英]How can i get a response from the server to a client message

我想知道如何将消息从服​​务器发送回客户端。 我是Java的新手,已经搜索了问题,但是所使用的代码不熟悉我所学的内容。 我尝试这样做,但是我无法完全将其发送回客户端。

一旦客户端将消息“ first”发送到服务器,我想从服务器向客户端发送“消息已重新整理的消息”。

任何帮助的解释将不胜感激!

客户代码:

import java.io.*;
import java.net.*;

public class Client {

//Main Method:- called when running the class file.
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on.
    int portNumber = 15882;
    //ServerIP:- IP address of the server.
    String serverIP = "localhost";

    try{
        //Create a new socket for communication
        Socket soc = new Socket(serverIP,portNumber);

        // create new instance of the client writer thread, intialise it and 
start it running
        ClientWriter clientWrite = new ClientWriter(soc);
        Thread clientWriteThread = new Thread(clientWrite);
        clientWriteThread.start();

    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing 
message to the console
        System.out.println("Error --> " + except.getMessage());
    }
  }
}

//This thread is responcible for writing messages
 class ClientWriter implements Runnable
 {
 Socket cwSocket = null;

 public ClientWriter (Socket outputSoc){
    cwSocket = outputSoc;
 }   
 public void run(){
    try{
        //Create the outputstream to send data through
        DataOutputStream dataOut = new 
DataOutputStream(cwSocket.getOutputStream());

        System.out.println("Client writer running");

        //Write message to output stream and send through socket
        dataOut.writeUTF("First");     // writes to output stream
        dataOut.flush();                       // sends through socket 

        //close the stream once we are done with it
        dataOut.close();
    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing 
message to the console
        System.out.println("Error in Writer--> " + except.getMessage());
    }
 }
}

class ClientListener implements Runnable
{
Socket clSocket = null;

public ClientListener (Socket inputSoc) {
    clSocket = inputSoc;
}

public void run() {
    try {

        // need to write here to recieve message 
        DataInputStream dataIn = new 
DataInputStream(clSocket.getInputStream());           // new stuff
        String msg = dataIn.readUTF();
        System.out.print(msg);

    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing 
message to the console
        System.out.println("Error in Writer--> " + except.getMessage());
    }
  }


}

服务器代码:

import java.io.*;
import java.net.*;

public class Serv {

//Main Method:- called when running the class file.
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on.
    int portNumber = 15882;
    try{
        //Setup the socket for communication 
        @SuppressWarnings("resource")
        ServerSocket serverSoc = new ServerSocket(portNumber);

        while (true){

            //accept incoming communication
            System.out.println("Waiting for client");
            Socket soc = serverSoc.accept();

            DataOutputStream dos = new 
DataOutputStream(soc.getOutputStream());
            dos.writeUTF("Message Recieved");                                                
// new stuff
            dos.flush();                         //need to flush

            //create a new thread for the connection and start it.
            ServerConnetionHandler sch = new ServerConnetionHandler(soc);
            Thread schThread = new Thread(sch);
            schThread.start();
        }
    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing 
message to the console
        System.out.println("Error --> " + except.getMessage());
    }
  }   
}

class ServerConnetionHandler implements Runnable
{
Socket clientSocket = null;

public ServerConnetionHandler (Socket inSoc){
    clientSocket = inSoc;
}

public void run(){
    try{
        //Catch the incoming data in a data stream, read a line and output 
it to the console
        DataInputStream dataIn = new 
DataInputStream(clientSocket.getInputStream());

        System.out.println("Client Connected");
        //Print out message
        System.out.println("--> " + dataIn.readUTF());

        //close the stream once we are done with it
        dataIn.close();
    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing 
message to the console
        System.out.println("Error in ServerHandler--> " + 
except.getMessage());
    }
   }
}

我已经找到了问题,并为您在两个类中都进行了修复,但是在我给您代码之前,让我们先谈谈为什么您的代码无法正常工作。

client代码中,您可以正确设置流,并连接到服务器,但是在尝试向服务器发送消息之后,便有了这段代码:

//close the stream once we are done with it
dataOut.close();

如果您稍后要等待响应,则不要关闭outputstream ,如果这是直接的单向消息,则是(Client-> Server),仅此而已,这没关系。 简单来说,因为有了它,它关闭了serverclient之间的套接字通信。

在那之后,我注意到您还有另一个名为ClientListener类,但可笑的是,它从未被调用过! 因此,当它尝试发送回信时,这将在服务器端导致错误,很明显,客户端没有监听任何内容。 因此,我对其进行了修复,并将此代码添加到ClientWriter类的try语句中。

ClientListener listener = new ClientListener(cwSocket);
new Thread(listener).start();

现在我们可以进入serv类,看看那里发生了什么。 我立即注意到的一个大问题是,一旦服务器初始化并等待client连接,它就将响应发送回客户端,而没有读取必须说的任何内容! 始终最好先阅读客户端向您发送的内容,然后再发送回任何数据,否则可能会导致错误。 但可惜,您有一个ServerConnectionHandler类来侦听传入的数据,但是在您将回复发送回client之后调用了该类。 它甚至应该在发送回复之前就已经在侦听,这不仅是为了防止错误,而且还可以侦听数据,因为在输出流写完某些内容之后,您将无法侦听数据(除非在我以其他方式缩短了serv班,但总体来说,对于初学者来说,这是很棒的工作! 以下是修改后的工作类:

客户

import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args){ 

//Portnumber:- number of the port we wish to connect on.
int portNumber = 15882;

//ServerIP:- IP address of the server.
String serverIP = "localhost";

try{
    //Create a new socket for communication
    Socket soc = new Socket(serverIP, portNumber);

    // create new instance of the client writer thread, intialise it and start it running
    ClientWriter clientWrite = new ClientWriter(soc);
    new Thread(clientWrite).start();
    //Shortened code a bit.

    //Thread clientWriteThread = new Thread(clientWrite);
    //clientWriteThread.start();





}
catch (Exception except){
    //Exception thrown (except) when something went wrong, pushing message to the console
    System.out.println("Error --> " + except.getMessage());
}
}}






//This thread is responcible for writing messages
class ClientWriter implements Runnable
 {

 Socket cwSocket = null;

 public ClientWriter (Socket outputSoc){
cwSocket = outputSoc;
 }   


public void run(){
try{
    //Create the outputstream to send data through
    DataOutputStream dataOut = new DataOutputStream(cwSocket.getOutputStream());

    System.out.println("Client writer running");

    //Write message to output stream and send through socket
    dataOut.writeUTF("First");     // writes to output stream
    dataOut.flush();               // sends through socket 

    //close the stream once we are done with it
    //dataOut.close();
        //Closing the stream will close the connection between the server and client.
        //DO NOT close an input stream or output stream when communicating with
        //each other, unless it is one way communication...


   //Where is the listener? It's never called, so we can't listen for anything!
   ClientListener listener = new ClientListener(cwSocket);
   new Thread(listener).start();

}
catch (Exception except){
    //Exception thrown (except) when something went wrong, pushing message to the console
    System.out.println("Error in Writer--> " + except.getMessage());
    except.printStackTrace();
}
 }
}




class ClientListener implements Runnable
{
Socket clSocket = null;

public ClientListener (Socket inputSoc) {
clSocket = inputSoc;
}

public void run() {
try {

    // need to write here to recieve message 
    DataInputStream dataIn = new DataInputStream(clSocket.getInputStream());           // new stuff
    String msg = dataIn.readUTF();
    System.out.print(msg);



}
catch (Exception except){
    //Exception thrown (except) when something went wrong, pushing message to the console
    System.out.println("Error in Writer--> " + except.getMessage());
    except.printStackTrace();
}
  }


}

服务器

import java.io.*;
import java.net.*;

public class Serv {

//Main Method:- called when running the class file.
public static void main(String[] args){ 

//Portnumber:- number of the port we wish to connect on.
int portNumber = 15882;
try{
    //Setup the socket for communication 
    ServerSocket serverSoc = new ServerSocket(portNumber);

    while (true){
        //accept incoming communication
        System.out.println("Waiting for client");
        Socket soc = serverSoc.accept();

        /* It's best to initialize both the input and output streams at the same time
         * Make sure you read what the other stream said before writing to it,
         * or it can be a cluttered error causing mess.
        */

        DataOutputStream dos = new DataOutputStream(soc.getOutputStream());
        DataInputStream dataIn = new DataInputStream(soc.getInputStream());



        //Read what client sent us
        System.out.println("Message Received: -->" + dataIn.readUTF());

        //Send reply back to client
        dos.writeUTF("Message Recieved");    // new stuff
        dos.flush();                         //need to flush


        //Close the inputstream and output stream so we can disconnect this user
        //and wait for another one to connect.
        dataIn.close();
        dos.close();


        //Can not read after writing back, doesn't make sense

        //create a new thread for the connection and start it.
        //ServerConnetionHandler sch = new ServerConnetionHandler(soc);
        //Thread schThread = new Thread(sch);
        //schThread.start();
    }
}
catch (Exception except){
    //Exception thrown (except) when something went wrong, pushing message to the console
    System.out.println("Error --> " + except.getMessage());
    except.printStackTrace();
}
}}



/*The last code you had was all wrong. Up in the server, you were
 * writing a reply back to the client and then waiting for a response...
 * You can't listen for something after you wrote back (failed to write back
 * anyway due to some problems)
 * You can remove this code below, as it is redundant.
 */
/*
class ServerConnetionHandler implements Runnable
{
Socket clientSocket = null;

public ServerConnetionHandler (Socket inSoc){
clientSocket = inSoc;
}

public void run(){
try{
    //Catch the incoming data in a data stream, read a line and output it to the console
    DataInputStream dataIn = new DataInputStream(clientSocket.getInputStream());

    System.out.println("Client Connected");
    //Print out message
    System.out.println("--> " + dataIn.readUTF());

    //close the stream once we are done with it
    dataIn.close();
}
catch (Exception except){
    //Exception thrown (except) when something went wrong, pushing message to the console
    System.out.println("Error in ServerHandler--> " + 
            except.getMessage());
}
   }*/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM