java.net-为什么客户端没有收到服务器的回复

时间:2014-04-23 17:54:13

标签: java sockets network-programming serversocket

这是客户端类,它接受来自用户(字和定义)的输入,并且客户端发送选择号(在这种情况下,选项号为1,表示添加一个字)+输入到服务器。

public class Client {

public static void main(String[] args) throws Exception {
    welcomeMessage();
    int choice=input();

    Scanner scan=new Scanner(System.in);
    Socket clientSocket=new Socket("localhost",8888);
    DataOutputStream toServer=new DataOutputStream(clientSocket.getOutputStream());
    BufferedReader inFromServer=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));


    String word;
    switch (choice) {

    case 1:
        System.out.println("Adding words\nEnter a word");
         word = scan.next();
        System.out.println("Enter definition");
        String definition = " ";


            definition += scan.nextLine();

        toServer.writeBytes(choice+";"+word+";"+definition+"\n");
        String str=inFromServer.readLine();

        System.out.println(str);
        break;
            //other cases
    }
    clientSocket.close();
}

这是服务器类。

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket welcomeSocket = new ServerSocket(8888);
        String clientData;
        String[] arr = new String[2];
        Vector<String[]> dictionary = new Vector<String[]>();
        System.out.println("hi");
        while (true) {


            Socket connectionSocket = welcomeSocket.accept();

            BufferedReader inFromClient = new BufferedReader(   
                    new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(
                    connectionSocket.getOutputStream());
            clientData = inFromClient.readLine();

            int index;
            int in=0;
            switch (clientData.charAt(0)) {
            case '1':   
                connectionSocket = welcomeSocket.accept();
                System.out.println("I'm in");

                if(dictionary.size()==0 || Bsearch(dictionary,getWord(clientData.substring(2)),0,dictionary.size())==-1){

                arr[0]=getWord(clientData.substring(2));
                arr[1]=getDefinition(clientData.substring(2));
                dictionary.add(in++,arr);

                outToClient.writeBytes("Added successfully");


                }
                else
                outToClient.writeBytes("Word already exists");
                welcomeSocket.close();
                break;
        }

    }

客户端类已成功发送到服务器,但服务器没有发回。有什么帮助吗?

我认为服务器中存在某种无限循环,因为客户端的代码没有进行,它会一直等待。

0 个答案:

没有答案