開(kāi)始...
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("客戶(hù)" + socket.getInetAddress().getHostAddress() + "來(lái)訪(fǎng),");
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("客戶(hù)端已退出,拜拜".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、客戶(hù)端程序:
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)
客戶(hù)端
cd com/kyy/bases/socket 運(yùn)行javac ClientSocketApp.java
cd classpath根目錄 運(yùn)行java ClientSocketApp
遇到的問(wèn)題:
如果不通過(guò)eclipse、Idea等工具,會(huì)出現(xiàn) “找不到或無(wú)法加載主類(lèi) com.kyy.bases.socket.ClientSocketApp”的異常
解決辦法,設(shè)置classpath=.;"JAVA_HOME"/lib
或者在cmd窗口臨時(shí)設(shè)置set classpath=.;
...結(jié)束
創(chuàng)新互聯(lián)www.cdcxhl.cn,專(zhuān)業(yè)提供香港、美國(guó)云服務(wù)器,動(dòng)態(tài)BGP最優(yōu)骨干路由自動(dòng)選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動(dòng)現(xiàn)已開(kāi)啟,新人活動(dòng)云服務(wù)器買(mǎi)多久送多久。