gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:01:26 25 4
gpt4 key购买 nike

下面是一个简单的套接字级程序。一旦建立连接,只要消息不以句点结束,服务器就可以讲多久,只要消息不以句点结束,那么客户端就可以讲多久,只要 session 不以句点结束。期间 - 对话就这样交替进行,直到有人关闭程序 -

直到有句号部分下来我才能得到......否则,我不会有问题 - 会有一对一的互动

一旦一个人写了,就永远轮到他们了......

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(".")){...}

关于java - 简单的套接字级程序-客户端/服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16618995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com