這是我的教師項目的簡單客戶端/服務器套接字應用程序。首先,運行Server類,然後如果Client類運行 - 它將輸出本地計算機的IP地址和使用的端口。java中的Socket客戶端/服務器停止方法
我想不通一兩件事:
在何處以及如何創造類中的方法,將關閉(停止)的服務器?而 如何使這就像一個事件或某事,例如,如果客戶 發出「停止」,它應該以某種方式停止服務器......
SERVER.JAVA
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
System.out.println("The server has been summoned.\n");
System.out.println("The server is waiting for client to come...");
try {
ServerSocket servertest = new ServerSocket(2014);
while (true) {
try {
Socket ser = servertest.accept();
new ThreadSer(ser).start();
} catch (IOException e) {}
}
} catch (IOException e) {System.err.println(e);}
}
public static class ThreadSer extends Thread {
private Socket s;
public ThreadSer(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
String response = "This is the IP: " + s.getLocalAddress() + " that has come via port: "
+ s.getLocalPort() + "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
} catch (IOException e) { System.err.println(e); }
}}}
CLIENT .JAVA
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 2014);
new OutputThread(socket.getInputStream()).start();
}
public static class OutputThread extends Thread {
private InputStream inputstream;
public OutputThread(InputStream inputstream) {
this.inputstream = inputstream;
}
@Override
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
while (true) {
try {
String line = input.readLine();
System.out.println(line);
} catch (IOException exception) {
exception.printStackTrace();
break;
}
}
}}}
你可以嘗試讓他們成線,然後thread.end();或沿線 – SemperAmbroscus
好東西,以至於我的互聯網速度很爛,所以我hadent看到他的答案在時間 – SemperAmbroscus