服务端
public static void main(String[] args) throws IOException {
int port = 30000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("====等待客户端连接=======");
Socket socket = serverSocket.accept();
System.out.println("===已连接:" + socket.isConnected() + "======");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String info = br.readLine();
if (!info.isEmpty()) {
System.out.println(info);
}
if (info.equals("exit")) {
br.close();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
serverSocket.close();
}
}
客户端
int port = 30000;
InetAddress address = InetAddress.getLocalHost();
Socket socket = new Socket(address,port);
System.out.println("=====已连接:"+ socket.isConnected()+"======");
OutputStream out = socket.getOutputStream();
PrintWriter pw = new PrintWriter(out,true);
String message ="您好,服务端!";
pw.println(message);
Scanner scanner = new Scanner(System.in);
while(true){
String s = scanner.nextLine();
pw.println(s);
if(s.equals("exit")){
break;
}
}
out.close();
pw.close();
socket.close();
Android Studio 不支持在同一个模块中运行两个JAVA 程序,它们的运行是同步的,因此需要重开一个Android Project.
|