您好,登錄后才能下訂單哦!
開始...
1、服務(wù)器端:
public class ServerSocketApp {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服務(wù)已啟動(dòng)");
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("請(qǐng)輸入:");
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、運(yùn)行
服務(wù)器
cd com/kyy/bases/socket 運(yùn)行javac ServerSocketApp.java
cd classpath根目錄 運(yùn)行java ServerSocketApp
服務(wù)器端啟動(dòng)
客戶端
cd com/kyy/bases/socket 運(yùn)行javac ClientSocketApp.java
cd classpath根目錄 運(yùn)行java ClientSocketApp
遇到的問題:
如果不通過eclipse、Idea等工具,會(huì)出現(xiàn) “找不到或無法加載主類 com.kyy.bases.socket.ClientSocketApp”的異常
解決辦法,設(shè)置classpath=.;"JAVA_HOME"/lib
或者在cmd窗口臨時(shí)設(shè)置set classpath=.;
...結(jié)束
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。