ServerApp.java
上传用户:caijun
上传日期:2022-08-05
资源大小:13k
文件大小:1k
- package ServerClientCommunication;
- import java.net.*;
- import java.io.*;
- public class ServerApp {
- public static void main(String args[]) {
- try {
- boolean flag = true;
- Socket clientSocket = null;
- String inputLine;
- int c;
- ServerSocket sSocket = new ServerSocket(8821);
- System.out.println("Server listen on:" + sSocket.getLocalPort());
- while (flag) {
- clientSocket = sSocket.accept();
- DataInputStream is = new DataInputStream(
- new BufferedInputStream(clientSocket.getInputStream()));
- OutputStream os = clientSocket.getOutputStream();
- while ((inputLine = is.readLine()) != null) {
- // 当客户端输入stop的时候服务器程式运行终止! when receive stop from client , stop the listen
- if (inputLine.equals("stop")) {
- flag = false;
- break;
- } else {
- System.out.println(inputLine);
- while ((c = System.in.read()) != -1) {
- os.write((byte) c);
- if (c == 'n') {
- os.flush(); // 将信息发送到客户端 send the message to client
- break;
- }
- }
- }
- }
- is.close();
- os.close();
- clientSocket.close();
- }
- sSocket.close();
- } catch (Exception e) {
- System.out.println("Exception :" + e.getMessage());
- }
- }
- }