-1

我有一个服务器如下:

import java.io.*;
import java.net.*;
import java.util.StringTokenizer;

public class MyTcpServer {

    static ServerSocket server = null;
    static Socket connectionSocket = null;
    static BufferedReader inFromClient = null;
    static PrintWriter outToClient = null;

    public static void initiateService() {
        try {
            server = new ServerSocket(1234);

            System.out.println("TCPServer Waiting for client on port 1234");
        } catch (IOException e) {
            System.out
                    .println("There is some error!! Please try some other port!");
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void awaitRequest() throws IOException {
        String instructionsToClient = null;
        System.out.println("Service Ready");
        while (true) {
            connectionSocket = server.accept();

            inFromClient = new BufferedReader(new InputStreamReader(
                    connectionSocket.getInputStream()));
            outToClient = new PrintWriter(connectionSocket.getOutputStream(),
                    true);

            String messageToClient;
            String messageFromClient = null;

            synchronized (Thread.currentThread()) {

                System.out.println("Client:"
                        + connectionSocket.getInetAddress()
                        + " connected on port :"
                        + connectionSocket.getLocalPort());

                messageToClient = "Welcome!!!! You are now connected to our server!! We ensure a reliable service.\n"
                        + "\n Your IP:"
                        + connectionSocket.getInetAddress()
                        + "  \n"
                        + connectionSocket.getLocalPort()
                        + "::::MESSAGE FROM SERVER::::\n"
                        + "Lets play Water jug puzzel!! You give me sizes of two water Jars\n"
                        + "And a desired level to be achieved! Ill tell you whether the problem\n"
                        + "is solvable or not!!\n"
                        + "Comprande~?\n"
                        + "Enter your choice Y/N \n"
                        + "--------------------------";

                synchronized (outToClient) {

                    outToClient.println(messageToClient);
                    outToClient.flush();

                    System.out.println("invite sent to the client!!");

                }

                synchronized (inFromClient) {

                    messageFromClient = inFromClient.readLine();
                    System.out.println("The user says: " + messageFromClient);

                }

                if (messageFromClient.equalsIgnoreCase("y")) {
                    messageToClient = "Wow!! awesome! Throw a challenge at me!"
                            + "\nEnter Large jug volume,Small jug volume,Desired level in comma separated fashion"
                            + "\nFor example (5,3,2)"
                            + "\n--------------------------";

                } else if (messageFromClient.equalsIgnoreCase("n")) {
                    messageToClient = "Great! we dont have a problem with you not playing the puzzel!"
                            + "Do you wanna exit? press q and smack Enter key!"
                            + "\n--------------------------";
                } else {
                    messageToClient = "psssst!!! Wanna quit??"
                            + "press q and smack Enter key!"
                            + "\n--------------------------";
                }

                synchronized (messageToClient) {

                    outToClient.println(messageToClient);
                    outToClient.flush();

                    System.out.println("reply sent to the client!!");

                }
                messageFromClient = "";
                synchronized (inFromClient) {
                    System.out.println("Entered");

                    messageFromClient = inFromClient.readLine();
                    System.out.println("The user says: " + messageFromClient);



                if (messageFromClient.equalsIgnoreCase("q")) {
                    System.out.println("ui");
                    messageToClient = "Thank you!!"
                            + "\n--------------------------";
                } else {
                    StringTokenizer st = new StringTokenizer(messageFromClient,
                            ",");

                    if (st.countTokens() != 3) {
                        messageToClient = "See! the input you gave has some problem!"
                                + "\n you havent followed the instructions properly"
                                + "\n Thank you!! Bye for now! come back later!"
                                + "\n--------------------------";
                    } else {
                        messageToClient = "Thanks! i am solving it!"
                                + "\n--------------------------";


                    }
                }
                }

                synchronized (messageToClient) {

                    outToClient.println(messageToClient);
                    outToClient.flush();

                    System.out.println("problem answered sent to the client!!");

                }

            }
        }
    }



    public static void main(String[] args) throws IOException {
        initiateService();
        awaitRequest();
    }

}

我有一个客户端访问这个特定的服务器!

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

public class MyTcpClient {

    static Socket clientSocket;
    static BufferedReader inFromUser;
    static PrintWriter outToServer;
    static BufferedReader inFromServer;

    public static void main(String argv[]) throws Exception {
        String FromServer;
        String ToServer;

        clientSocket = new Socket("localhost", 1234);

        // for user to type messages in client mode
        inFromUser = new BufferedReader(new InputStreamReader(System.in));

        // client program uses this to write on the server
        outToServer = new PrintWriter(clientSocket.getOutputStream(), true);

        // servers talk back to the client
        inFromServer = new BufferedReader(new InputStreamReader(
                clientSocket.getInputStream()));

        FromServer = "";
        while (!FromServer.equals("--------------------------")) {
            FromServer = readFromServer();
            System.out.println(FromServer);

        }


        System.out.println("Enter choice!");
        String choice = "";

        choice = inFromUser.readLine();
        System.out.println("" + choice);

        synchronized (outToServer) {

            outToServer.println(choice);
            outToServer.flush();
        }

        FromServer = "";
        while (!FromServer.equals("--------------------------")) {
            FromServer = readFromServer();
            System.out.println(FromServer);

        }

        choice = inFromUser.readLine();
        System.out.println("" + choice);

        synchronized (outToServer) {

            outToServer.println(choice);
            outToServer.flush();
        }

        FromServer = "";
        while (!FromServer.equals("--------------------------")) {
            FromServer = readFromServer();
            System.out.println(FromServer);
        }

    }

    static String readFromServer() throws IOException {
        String response = inFromServer.readLine();
        return response;
    }

}

在成功运行时,服务器端的输出是这样的:

TCPServer Waiting for client on port 1234
Service Ready
Client:/127.0.0.1 connected on port :1234
invite sent to the client!!
The user says: y
reply sent to the client!!
Entered
The user says: 5,3,2

客户端的输出是这样的:

Welcome!!!! You are now connected to our server!! We ensure a reliable service.

 Your IP:/127.0.0.1  
1234::::MESSAGE FROM SERVER::::
Lets play Water jug puzzel!! You give me sizes of two water Jars
And a desired level to be achieved! Ill tell you whether the problem
is solvable or not!!
Comprande~?
Enter your choice Y/N 
--------------------------
Enter choice!
y
y
Wow!! awesome! Throw a challenge at me!
Enter Large jug volume,Small jug volume,Desired level in comma separated fashion
For example (5,3,2)
--------------------------
5,3,2
5,3,2
Exception in thread "main" java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    at MyTcpClient.readFromServer(MyTcpClient.java:85)
    at MyTcpClient.main(MyTcpClient.java:78)

此处引发的异常仅在提供以逗号分隔的字符串时。不知道出了什么问题,有人可以分享吗?

4

2 回答 2

1

我不打算尝试您的代码,但正如两个人已经尝试过的那样,我认为问题可能不在于您的代码。

看看这个

于 2012-08-02T05:17:47.013 回答
1

您的代码中还有其他一些问题:

static ServerSocket server = null;

不应该是静态的。

static Socket connectionSocket = null;

既不应该是静态的,也不应该是实例成员。它应该是调用accept()的方法中的一个局部变量。

static BufferedReader inFromClient = null;
static PrintWriter outToClient = null;

在这种情况下同上,但在一般情况下,它们应该是您为每个新接受的套接字实例化的每个连接类的实例成员。这通常是Runnable,run()方法为该客户端执行所有 I/O,或调用执行此操作的方法。

于 2012-08-02T05:54:02.153 回答