java 监听socket

        @Test
	public void run() throws IOException {
		AcceptThread acceptThread = new AcceptThread();
		acceptThread.run();
	}

	class AcceptThread extends Thread {
		public void run() {
			ServerSocket serverSocket = null;
			Socket socket = null;
			DataInputStream input = null;

			try {
				serverSocket = new ServerSocket(3600);
				socket = serverSocket.accept();
				socket.setKeepAlive(true);

				while (true) {
					input = new DataInputStream(socket.getInputStream());
					byte[] buffer = {};
					int bufflenth = input.available();
					int size = 0;
					while (bufflenth != 0) {
						// 初始化byte数组为buffer中数据的长度
						buffer = new byte[bufflenth];
						size += input.read(buffer);
						bufflenth = input.available();
					}
					if (buffer.length != 0) {
						String str = new String(buffer, "GB2312");
						System.out.println("接收到:" + str);
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (input != null) {
						input.close();
						input = null;
					}
					if (socket != null) {
						socket.close();
						socket = null;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_32534855/article/details/81474777