您好,登錄后才能下訂單哦!
開始...
1、服務器端:
public class ServerSocketApp {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服務已啟動");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客戶" + socket.getInetAddress().getHostAddress() + "來訪,");
new Thread(() -> {
try {
InputStream inputStream = socket.getInputStream();
PrintStream printStream = new PrintStream(socket.getOutputStream());
Scanner in = new Scanner(inputStream);
in.useDelimiter("\n");
while (in.hasNext()) {
String message = in.next().trim();
if (message.equalsIgnoreCase("bye")) {
String bye = new String("客戶端已退出,拜拜".getBytes("UTF-8"));
System.out.println(bye);
printStream.println(bye);
} else {
printStream.println("ECHO>" + message);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、客戶端程序:
public class ClientSocketApp {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 9999);
Scanner in = new Scanner(System.in);
Scanner inputStream = new Scanner(socket.getInputStream());
PrintStream printStream = new PrintStream(socket.getOutputStream());
in.useDelimiter("\n");
inputStream.useDelimiter("\n");
boolean b = true;
System.out.println("請輸入:");
while (b) {
if (in.hasNext()) {
String message = in.next().trim();
printStream.println(message);
if (inputStream.hasNext()) {
String serverMessage = new String(inputStream.next().trim().getBytes("UTF-8"));
System.out.println(serverMessage);
}
if (message.equalsIgnoreCase("bye")) {
b = false;
}
}
}
socket.close();
}
}
3、運行
服務器
cd com/kyy/bases/socket 運行javac ServerSocketApp.java
cd classpath根目錄 運行java ServerSocketApp
服務器端啟動
客戶端
cd com/kyy/bases/socket 運行javac ClientSocketApp.java
cd classpath根目錄 運行java ClientSocketApp
遇到的問題:
如果不通過eclipse、Idea等工具,會出現 “找不到或無法加載主類 com.kyy.bases.socket.ClientSocketApp”的異常
解決辦法,設置classpath=.;"JAVA_HOME"/lib
或者在cmd窗口臨時設置set classpath=.;
...結束
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。