简单的套接字级程序 - 客户端/服务器

时间:2013-05-17 22:54:18

标签: java sockets

以下是一个简单的套接字级程序。一旦建立了连接,服务器只要他/她想要提供该消息没有在一段时间内结束就会说话 - 然后只要他/她想要提供该对话没有结束,客户端就可以说话。期间 - 对话交替出现,直到有人关闭程序 -

直到有一段时间部分失败我才能得到... 否则,我不会有问题 - 会有一对一的互动

一旦有人写道,它永远都会轮到他们......

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

public class ChatterServer {

    final static int SERVER_PORT = 3333;
    public static void main(String [] args) throws Exception {

        ServerSocket serverSocket = new ServerSocket(SERVER_PORT); 
        System.err.println("Waiting for a client");
        Socket clientSocket = serverSocket.accept();

        System.out.println("Connection requested from: " + clientSocket.getLocalAddress());

        PrintStream toClient = new PrintStream(clientSocket.getOutputStream(), true);
        BufferedReader fromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

        toClient.println("Whatcha want?"); 
        String incoming = fromClient.readLine();

        while(incoming != null) {

            System.out.println(incoming);
            System.out.print("Your turn>"); 
            String myReply="";

            //this part does not work
            while ( myReply.substring( myReply.length() ) .equals(".") == false){

                myReply = keyboard.readLine(); 
                toClient.println(myReply); 
            }

            incoming = fromClient.readLine();
        }
    }
}

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

public class ChatterClient {
    final static int SERVER_PORT = 3333;
    public static void main(String [] args) throws Exception {

        Socket serverSocket = new Socket(args[0], SERVER_PORT);
        PrintStream toServer =
                new PrintStream(serverSocket.getOutputStream(), true);
        BufferedReader fromServer = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
        BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

        String incoming = fromServer.readLine();

        while(incoming != null) { 
            System.out.println(incoming);
            System.out.print("Your turn>"); 
            String myReply="";

            while ( myReply.substring( myReply.length() ) .equals(".") == false){
                myReply = keyboard.readLine(); 
                toServer.println(myReply); 
            }//end while

            incoming = fromServer.readLine();
        }//end while
    }//end main

}//end ChatterClient class

2 个答案:

答案 0 :(得分:2)

最好使用endsWith方法。它会工作得很好,看起来更干净。

 while (!myReply.endsWith(".")){...}

答案 1 :(得分:0)

虽然我同意使用String.endsWith,但代码中的实际问题是someString.substring(someString.length()) 总是是一个空字符串。你想要someString.substring(someString.length()-1)