socketclient.java
来自「Java the UML Way 书中所有源码」· Java 代码 · 共 60 行
JAVA
60 行
/*
* SocketClient.java E.L. 2001-08-25
*/
import java.io.*;
import java.net.*;
class SocketClient {
public static void main(String[] args) {
try {
/* Input will be read from the console, see section 11.7 */
InputStreamReader readingConnToConsole = new InputStreamReader(System.in);
BufferedReader fromConsoleReader = new BufferedReader(readingConnToConsole);
/* Inputs name of the server machine from the user*/
System.out.print("The name of the machine where the server program is running: ");
String serverMachine = fromConsoleReader.readLine();
/* Contacts the server program */
Socket connection = new Socket(serverMachine, 1250);
System.out.println("Now the connection to the server program is established.");
/* Opens streams to the server program */
InputStreamReader readConnection
= new InputStreamReader(connection.getInputStream());
BufferedReader fromServerReader = new BufferedReader(readConnection);
PrintWriter toServerWriter = new PrintWriter(connection.getOutputStream(), true);
/* Receives the introductory text from the server, and prints it to the console */
String intro1 = fromServerReader.readLine();
String intro2 = fromServerReader.readLine();
System.out.println(intro1 + "\n" + intro2);
/* Inputs one line of text from the console (the user) */
String aLine = fromConsoleReader.readLine();
while (!aLine.equals("")) {
toServerWriter.println(aLine); // sends the text to the server program
String response = fromServerReader.readLine(); // receives response from the server
System.out.println(response);
aLine = fromConsoleReader.readLine();
}
connection.close(); // shuts down the connection
} catch (Exception e) {
System.out.println("Error on the client side: " + e);
}
}
}
/* Example Run:
Output at the client side:
The name of the machine where the server program is running: mary.marysHome.dk
Now the connection to the server program is established.
***Hello, you are connected to the server side!
***Write what you want, then I will repeat it. End with a carriage return.
Hello, this is a test!
***You wrote: Hello, this is a test!
Yes, I did! It works!
***You wrote: Yes, I did! It works!
*/
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?