服务器套接字Java没有响应

时间:2016-03-23 22:33:18

标签: java sockets

请帮助,已建立与服务器的连接,但服务器不会响应任何请求。只是尝试通过发送服务器“1”来获取时间和日期。 P.s我知道我不应该拥有1-7的所有案例,但我只想在担心其他人之前得到日期广告时间

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;

/**
 *
 * @author samdo
 */
public class SocketProgrammingSamD {

    /**
     * @param args the command line arguments
     */

    private static Scanner in;
    public static void main(String[] args) throws IOException {
        System.out.println("Samuel Donini");
        System.out.println("                           ");
        System.out.println("Project 1");
        System.out.println("                           ");
        System.out.println("                           ");
        //new Driver().execute(args);//Creates an instance of the Driver class and Calls the Driver.execute method

        in = new Scanner(System.in);
        System.out.println("(Client) Enter Server Ip to Connect to(Empty will give localhost):");
        String ip = in.nextLine();
        System.out.println("(Client) Enter your server port no:");
        int port = in.nextInt();
        if (ip == null || ip.length() == 0) {
            ip = "localhost";
        }
        System.out.println("Connecting to " + ip + ":" + port);
        // for taking input from client
        // InputStream inputStream = connectionSocket.getInputStream();

        // Try to connect to port and the IP address given on the command line.
        try (Socket socket = new Socket(ip, port)) {

            // for taking input from client
            // InputStream inputStream = connectionSocket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(System.in);
            BufferedReader inputFromClient = new BufferedReader(inputStreamReader);
            // for giving output to the client.
            OutputStream outputStream = socket.getOutputStream();
            // output to client, to send data to the server
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            // get output from server
            InputStream serverInputStream = socket.getInputStream();
            InputStreamReader inputStreamReaderFromServer = new InputStreamReader(
                    serverInputStream);
            BufferedReader bufferReader = new BufferedReader(
                    inputStreamReaderFromServer);
            //System.out.println("(Client) Give input:");

             System.out.printf("Menu Options:\t\t\tCommands\n"); 
        System.out.printf("-------------\t\t\t--------\n"); 
        System.out.printf(" * 1 current Date & Time:\t1\n"); 
        System.out.printf(" * 2 uptime: \t\t        2\n"); 
        System.out.printf(" * 3 memory use: \t\t3\n"); 
        System.out.printf(" * 4 Netstat: \t\t        4\n"); 
        System.out.printf(" * 5 current users: \t\t5\n"); 
        System.out.printf(" * 6 disk usage: \t\t6\n"); 
        System.out.printf(" * 7 Quit: \t\t\t7\n\n");


            String readingLineFromUser = inputFromClient.readLine();
            // sending data to server
            dataOutputStream.writeBytes(readingLineFromUser + "\n");

            String getStringFromServer = bufferReader.readLine();

            System.out.println("Got input from server (in client):" + getStringFromServer);

            //attempts to get System Time
            System.out.println("Requesting system time");
            System.out.println("1");
//System.out.write("Server Date" + (new Date()).toString() + "\n");
            System.out.println("Response from the server:\n");

        // Read lines from the server and print them until "ServerDone" on
            // a line by itself is encountered.
            String answer;
            while ((answer = inputFromClient.readLine()) != null && !answer.equals("ServerDone")) {
                System.out.println(answer);
            }
            return;
        }

    }
}



import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

public class Server {

    private static ServerSocket severSocket;
    private static Scanner in;

    public static void main(String[] args) throws IOException {
        in = new Scanner(System.in);
        System.out.println("(Server) Enter your server port no:");
        int port = in.nextInt();
        System.out.println("Server Estabilsh Connection On Localhost or own ip with port : " + port);
        severSocket = new ServerSocket(port);

        System.out.println("Now you can run your client app.");

        while (true) {
            Socket connectionSocketListens = severSocket.accept();//Listens for a connection to be made to this socket and accepts it.
            System.out.println("Accepted Client connection");
            // for taking input from client
            InputStream inputStream = connectionSocketListens.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader inputFromClient = new BufferedReader(
                    inputStreamReader);
            // for giving output to the client.
            OutputStream outputStream = connectionSocketListens.getOutputStream();
            // output to client, to send data to the server
            DataOutputStream dataOutputStream = new DataOutputStream(
                    outputStream);
            // get output from server

            String readingLineFromClientSocket = inputFromClient.readLine();
            // sending data to client
            String modified = doOperation(readingLineFromClientSocket);
            // send data to client
            dataOutputStream.writeBytes(modified + "\n");

            // Read the request from the client! *** input = inputFromClient
            String answer = inputFromClient.readLine();
            System.out.println("Request from client "+answer);
            Process cmdProc;
            cmdProc = null;
            // Execute the appropriate command.
            if (answer.charAt(0) == '1') {
                System.out.println("Responding to date and time request from the client ");
                cmdProc = Runtime.getRuntime().exec("date");//MUST ADD TIME
            }
            if (answer.charAt(0) == '2') {
                System.out.println("Responding to uptime request from the client ");
                cmdProc = Runtime.getRuntime().exec("date");//MUST CHANGE
            }
            if (answer.charAt(0) == '3') {
                System.out.println("Responding to memory use request from the client ");
                cmdProc = Runtime.getRuntime().exec("date");
            }
            if (answer.charAt(0) == '4') {
                System.out.println("Responding to Netstat request from the client ");
                cmdProc = Runtime.getRuntime().exec("date");
            }
            if (answer.charAt(0) == '5') {
                System.out.println("Responding to current users request from the client ");
                cmdProc = Runtime.getRuntime().exec("date");
            }
            if (answer.charAt(0) == '6') {
                System.out.println("Responding to disk usage request from the client ");
                cmdProc = Runtime.getRuntime().exec("date");
            }
            if (answer.charAt(0) == '7') {
                System.out.println("Responding to Quit request from the client ");
                cmdProc = Runtime.getRuntime().exec("date");
            }
            else {
                System.out.println("Unknown request ");
                //need a socket.close or Server.close(); or something like that
                return;
            }
            //Read the result of the commands and sent the result to the client one line at a time
        // followed by the line "ServerDone"
            BufferedReader cmdin = new BufferedReader(new InputStreamReader(cmdProc.getInputStream()));
            String cmdans;
            while ((cmdans = cmdin.readLine()) != null) {
                System.out.println(cmdans);
            }
            System.out.println("ServerDone");


            return;

        }

    }

    private static String doOperation(String readingLineFromClientSocket) {
        String[] array = readingLineFromClientSocket.split(" ");
        StringBuilder strBuilder = new StringBuilder(array.length);

        for (int i = array.length - 1; i >= 0; i--) {
            String s = charReverse(array[i]);
            strBuilder.append(s);
            strBuilder.append(" ");
        }

        return strBuilder.toString();

    }

    private static String charReverse(String str) {
        return new StringBuilder(str).reverse().toString();
    }
}

1 个答案:

答案 0 :(得分:0)

我做了以下更改后有一个工作版本:

我在Server类中更改了此代码:

String answer = inputFromClient.readLine();

//String answer = inputFromClient.readLine();
String answer = modified;
System.out.println("Request from client "+answer);    

所有的行如下(除了第一行):

if (answer.charAt(0) == '2')

需要

else if (answer.charAt(0) == '2')

和 - 至少在Windows上 - 以下行:

cmdProc = Runtime.getRuntime().exec("date");

需要

cmdProc = Runtime.getRuntime().exec("cmd /c date /T");

这一行:

while ((answer = inputFromClient.readLine()) != null && !answer.equals("ServerDone")) {

应该是:

while ((answer = bufferReader.readLine()) != null && !answer.equals("ServerDone")) {

在此之后:

System.out.println(cmdans);

你需要:

dataOutputStream.writeBytes(cmdans + "\n");