[英]PrintWriter and OutputStream for a simple client server socket program
[英]Simple socket-level program - client/server
以下是一个简单的套接字级程序。 一旦建立了连接,服务器只要他/她想要提供该消息没有在一段时间内结束就会说话 - 然后只要他/她想要提供该对话没有结束,客户端就可以说话。期间 - 对话交替出现,直到有人关闭程序为止 -
我不能得到直到有一段时间部分下来...否则,我不会有问题 - 会有一个一个互动
一旦有人写道,它就会永远停留在他们身边......
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
更好的方法是使用endsWith
方法。 它会工作得很好,看起来更干净。
while (!myReply.endsWith(".")){...}
虽然我同意使用String.endsWith
,但代码中的实际问题是someString.substring(someString.length())
将始终为空字符串。 你想要someString.substring(someString.length()-1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.