我对套接字有点新意,我正在尝试编写一个程序,我基本上可以从Client程序向Server程序发送一些简单的请求。现在我只想在客户端中拥有用户可以选择的1或2个选项。例如,如果用户在客户端中选择“选项1”,则服务器会发回一条消息“您选择选项1”,依此类推,但我无法弄清楚如何读取已从客户端发送的服务器上的输入。
客户代码:
Socket socket = null;
try
{
System.out.println("Connecting to Server");
socket = new Socket("192.168.0.104", 7003);
socket.setSoTimeout(10000);
System.out.println("Connected");
InputStreamReader input = new InputStreamReader(socket.getInputStream());
BufferedReader buffer = new BufferedReader(input);
PrintWriter print = new PrintWriter(socket.getOutputStream(), true);
String line = buffer.readLine();
//Not Sure which buffer to user here
System.out.println("Option 1");
System.out.println("Option 2");
System.out.println("Option 3");
}
System.out.println("Closing Client Connection");
buffer.close();
input.close();
print.close();
socket.close();
System.exit(0);
服务器代码:
ServerSocket serverSock = null;
Socket standSock = null;
try
{
serverSock = new ServerSocket(7003);
standSock = serverSock.accept();
InputStreamReader input = new InputStreamReader(standSock.getInputStream());
BufferedReader read = new BufferedReader(input);
PrintWriter print = new PrintWriter(standSock.getOutputStream(), true);
String dateTime = (Calendar.getInstance()).getTime().toString();
print.println("You're connected to the Server at: " + dateTime);
print.println("Type Q to disconnect");
String line = read.readLine();
//Not sure what to do here
System.out.println("Client: " + line);
print.println("Server" + line);
System.out.println("Closing Server Connection");
read.close();
input.close();
print.close();
standSock.close();
我需要在Clinet中使用两个不同的BufferedReader,一个用于用户输入,一个用于socket?真的很困惑这个部分。
由于
答案 0 :(得分:1)
客户端需要读取用户的输入并将其发送到服务器。服务器需要从套接字读取并响应套接字。客户端必须从套接字读取并向用户提供适当的消息。服务器不会直接通过客户端直接读取或写入任何内容。