OOP h16
完成 MyServer 类,随机测试向服务器端输入几句话,要求服务器端原封不动返回,向服务器端输入 bye ,表示断开连接。
开始没有完全理解,需要启动线程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
package com.huawei.classroom.student.h16;
public class MyServer {
public MyServer() { }
public void startListen(int port) { Thread serverThread = new ServerThread(port); serverThread.start(); } }
|
新建 ServerThread 类继承 Thread,用于监听端口。
会用到的成员变量:
1 2 3 4 5 6 7
| private final int port; private ServerSocket server; private Socket socket; private InputStream in; private OutputStream out; private static final int MAX_LEN = 100; private static final String STOP_STRING = "bye" + "\r\n";
|
构造方法:
1 2 3 4 5 6 7
| public ServerThread(int port) { server = null; socket = null; in = null; out = null; this.port = port; }
|
重写 run
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| @Override public void run() { try { server = new ServerSocket(port); socket = server.accept(); in = socket.getInputStream(); out = socket.getOutputStream(); byte[] data = new byte[MAX_LEN]; int readed = in.read(data); String line = new String(data, 0, readed); while (!STOP_STRING.equals(line)) { out.write(line.getBytes()); readed = in.read(data); line = new String(data, 0, readed); } in.close(); out.close(); socket.close(); server.close(); } catch (IOException e) { e.printStackTrace(); } finally { close(in); close(out); close(socket); close(server); } } public void close(Closeable inout) { if (inout != null) { try { inout.close(); } catch (IOException e) { e.printStackTrace(); } } }
|
终于忙完了,一年的大创结束了……