public void run() { while (true) { LinkedList<PacketCallbackStruct> list = null; try { queuedPacketCallbacksLock.lock(); try { queuedPacketCallbacksNotEmpty.await(); } catch (Exception e) { Log.error( "RDPServer.PacketCallbackThread: queuedPacketCallbacksNotEmpty.await() caught exception " + e.getMessage()); } list = queuedPacketCallbacks; queuedPacketCallbacks = new LinkedList<PacketCallbackStruct>(); } finally { queuedPacketCallbacksLock.unlock(); } if (Log.loggingNet) Log.net("RDPServer.PacketCallbackThread: Got " + list.size() + " queued packets"); for (PacketCallbackStruct pcs : list) { try { callbackProcessPacket(pcs.cb, pcs.con, pcs.packet); } catch (Exception e) { Log.exception("RDPServer.PacketCallbackThread: ", e); } } } }
public static void listen(StringTokenizer st) { try { if (port[0] == -1) { if (st.hasMoreTokens()) { try { port[0] = Integer.parseInt(st.nextToken()); } catch (NumberFormatException nfe) { System.err.println("listen: incorrect port name"); return; } if (port[0] < 0 || port[0] > 65535) { System.err.println("listen: port name is out of range 0 - 65535"); port[0] = -1; return; } if (!serverSocket.isOpen()) { serverSocket = ServerSocketChannel.open(); serverSocket.configureBlocking(false); } serverSocket.socket().bind(new InetSocketAddress(port[0])); serverSocket.register(selector, SelectionKey.OP_ACCEPT); } else { System.err.println("listen: no port name"); } } else { System.err.println("Error: already listening port " + port[0]); } } catch (Exception expt) { Utils.printErrorAndExit(expt.getMessage()); } }
public static void sendMessage(SocketChannel clientSocket, byte[] message) { try { if (clientSocket.isConnected()) { clientSocket.write(ByteBuffer.wrap(message)); } } catch (Exception expt) { Utils.printErrorAndExit("Error: " + expt.getMessage()); } }
public void run() { try { // trimitere pachet pe sochet this.server.doWrite(this.key); } catch (Exception e) { System.err.println("WriteJob exception: " + e); e.printStackTrace(); } }
public static void main(String[] args) throws Exception { init(); String mainPath = args.length > 0 ? args[0] : "0inicio.js"; try { jsLoad("librt.js", null, args); jsLoad(mainPath, null, args); } catch (Exception ex) { ex.printStackTrace(); logmex("ERR", 1, "RT RUNNING SCRIPTS", null, ex); } }
/** Registers a SelectableQueue */ public boolean register(SelectableQueue sq, Communicator communicator) { try { // Register the new pipe with the queue. It will write a byte to this // pipe when the queue is hot, and it will offer its communicator to our // queue. sq.register(this, communicator); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
public void run() { while (!shutdown) { try { registerTargets(); if (selector.select() > 0) { processSelectedKeys(); } } catch (Exception e) { e.printStackTrace(); } } try { selector.close(); } catch (IOException e) { e.printStackTrace(); } }
void show() { // 打印任务执行的结果 String result; if (connectFinish != 0) result = Long.toString(connectFinish - connectStart) + "ms"; else if (failure != null) result = failure.toString(); else result = "Timed out"; System.out.println(address + " : " + result); shown = true; }
public static void logmex(String t, int lvl, String msg, Object o, Exception ex) { StringBuilder sb = new StringBuilder(); StackTraceElement se[] = ex.getStackTrace(); for (int i = 0; i < se.length; i++) { sb.append(se[i].getMethodName() + "@" + se[i].getFileName() + "@" + se[i].getLineNumber()); sb.append(" > "); } logm(t, lvl, msg + " EXCEPTION " + ex + " " + sb.toString(), o); }
protected void accept_loop() { while (isRunning()) { try { SocketChannel client_channel = server_channel.accept(); last_accept_time = SystemTime.getCurrentTime(); client_channel.configureBlocking(false); listener.newConnectionAccepted(server_channel, client_channel); } catch (AsynchronousCloseException e) { /* is thrown when stop() is called */ } catch (Throwable t) { Debug.out(t); try { Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } } } }
public static void main(String[] args) { port[0] = -1; try { reader = new BufferedReader(new InputStreamReader(System.in)); clients = new LinkedHashMap<String, SocketChannel>(); selector = Selector.open(); List<SocketChannel> anonymousClients = new ArrayList<SocketChannel>(); serverSocket = ServerSocketChannel.open(); serverSocket.configureBlocking(false); while (true) { readCommand(); checkClients(anonymousClients); } } catch (Exception expt) { Utils.printErrorAndExit("Error: " + expt.getMessage()); } }
public static void kill(StringTokenizer st) { try { if (st.hasMoreTokens()) { String clientName = st.nextToken(); if (clients.containsKey(clientName)) { SocketChannel clientChannel = clients.get(clientName); clients.remove(clientName); sendMessage(clientChannel, MessageUtils.bye()); notifyAllClients(clientName + " leave this chatroom"); System.out.println(clientName + " leave this chatroom"); Utils.tryClose(clientChannel); } else { System.err.println("kill: no such client"); } } else { System.err.println("kill: no client name"); } } catch (Exception expt) { Utils.printErrorAndExit(expt.getMessage()); } }
public static void stop() { try { if (port[0] != -1) { for (Entry<String, SocketChannel> client : clients.entrySet()) { if (client.getValue().isConnected()) { sendMessage(client.getValue(), MessageUtils.bye()); Utils.tryClose(client.getValue()); } } Utils.tryClose(serverSocket); clients.clear(); port[0] = -1; } else { System.err.println("stop: already stopped"); } } catch (Exception expt) { Utils.printErrorAndExit(expt.getMessage()); } }
static void callbackProcessPacket( ClientConnection.MessageCallback pcb, ClientConnection clientCon, RDPPacket packet) { if (packet.isNul()) { return; } byte[] data = packet.getData(); MVByteBuffer buf = new MVByteBuffer(data); RDPConnection con = (RDPConnection) clientCon; // If this is a multiple-message message . . . if (buf.getLong() == -1 && buf.getInt() == RDPConnection.aggregatedMsgId) { con.aggregatedReceives++; PacketAggregator.allAggregatedReceives++; // Get the count of sub buffers int size = buf.getInt(); con.receivedMessagesAggregated += size; PacketAggregator.allReceivedMessagesAggregated += size; if (Log.loggingNet) Log.net( "RDPServer.callbackProcessPacket: processing aggregated message with " + size + " submessages"); MVByteBuffer subBuf = null; for (int i = 0; i < size; i++) { try { subBuf = buf.getByteBuffer(); } catch (Exception e) { Log.error("In CallbackThread, error getting aggregated subbuffer: " + e.getMessage()); } if (subBuf != null) pcb.processPacket(con, subBuf); } } else { con.unaggregatedReceives++; PacketAggregator.allUnaggregatedReceives++; buf.rewind(); pcb.processPacket(con, buf); } }
public static void main(String[] args) { try { System.out.println("CliTest.java"); // create TCP socket channel SocketChannel channel = SocketChannel.open(); System.out.println("CliTest.java: channel created"); channel.connect(new InetSocketAddress("localhost", PORT)); System.out.println("CliTest.java: channel socket connected"); System.out.println(); // create & send a login message byte[] bytes = LoginMessage.getLoginMessage("user1", "password1"); System.out.println("CliTest.java: login message created"); System.out.println(LoginMessage.getMessageString(bytes)); System.out.printf("CliTest.java: login message length in bytes: %d\n", bytes.length); ByteBuffer buf = ByteBuffer.allocate(4096); buf.put(bytes); buf.flip(); // System.out.printf("CliTest.java: buf.remaining before channel.write(): %d\n", // buf.remaining()); int numwritten = channel.write(buf); System.out.printf( "CliTest.java: login mesage written: number of bytes written: %d\n", numwritten); // read reply message buf.clear(); int numread = channel.read(buf); bytes = new byte[numread]; buf.flip(); buf.get(bytes); if (LoginMessage.isLoginSuccessMessage(bytes)) { System.out.printf( "CliTest.java: first message read: Success Message: number of bytes read: %d\n", numread); // get remote port number from success message int port = LoginMessage.getPort(bytes); System.out.printf("Port Number: %d\n", port); byte playerid = LoginMessage.getPlayerId(bytes); System.out.printf("Player id: %d\n", playerid); String mcastString = LoginMessage.getMulticastAddress(bytes); System.out.printf("Multicast Address: %s\n", mcastString); // create datagram channel & connect to rem port DatagramChannel dchannel = DatagramChannel.open(); dchannel.socket().bind(new InetSocketAddress(0)); dchannel.socket().connect(new InetSocketAddress(channel.socket().getInetAddress(), port)); // get localport of datagram socket int localport = dchannel.socket().getLocalPort(); System.out.printf("UDP local port: %d\n", localport); // send success message to send port number to server bytes = LoginMessage.getLoginSuccessMessage(playerid, null, localport); buf.clear(); buf.put(bytes); buf.flip(); channel.write(buf); DeathMessage dm = new DeathMessage((byte) 1, (byte) 1); bytes = dm.getByteMessage(); buf.clear(); buf.put(bytes); buf.flip(); channel.write(buf); } else { System.out.printf( "CliTest.java: first message read: NOT Success Message: number of bytes read: %d\n", numread); } channel.close(); } catch (Exception e) { e.printStackTrace(); } }
public static void readCommand() { try { if (!reader.ready()) { return; } StringTokenizer tokens = new StringTokenizer(reader.readLine()); if (tokens.hasMoreTokens()) { switch (tokens.nextToken()) { case "/listen": listen(tokens); break; case "/stop": stop(); break; case "/list": if (port[0] == -1) { System.err.println("Error: start listening before"); } for (Entry<String, SocketChannel> client : clients.entrySet()) { System.out.println(client.getKey()); } if (clients.entrySet().isEmpty()) { System.out.println("list: no clients online"); } break; case "/send": if (tokens.hasMoreTokens()) { String name = tokens.nextToken(); if (clients.containsKey(name)) { if (tokens.hasMoreTokens()) { sendMessage( clients.get(name), MessageUtils.message("<server>", getMessageFromTokens(tokens))); } else { System.err.println("send: message is empty"); } } else { System.err.println("send: no such client"); } } else { System.err.println("send: no client name"); } break; case "/sendall": if (tokens.hasMoreTokens()) { notifyAllClients(getMessageFromTokens(tokens)); } else { System.err.println("sendall: message is empty"); } break; case "/kill": kill(tokens); break; case "/exit": if (port[0] != -1) { stop(); } Utils.tryClose(selector); System.exit(0); break; default: System.err.print("Error: unknown command"); break; } } else { System.err.println("Error: empty input"); } } catch (Exception expt) { Utils.printErrorAndExit(expt.getMessage()); } }
public static void checkClients(List<SocketChannel> anonymousClients) { try { if (selector.selectNow() == 0) { return; } Set<SelectionKey> keys = selector.selectedKeys(); for (SelectionKey key : keys) { if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { SocketChannel clientSocket = serverSocket.accept(); if (clientSocket == null) { System.err.println("Error: can not accept"); continue; } anonymousClients.add(clientSocket); clientSocket.configureBlocking(false); clientSocket.register(selector, SelectionKey.OP_READ); } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { SocketChannel clientSocket = (SocketChannel) key.channel(); ByteBuffer bytes = ByteBuffer.allocate(4096); if (clientSocket.read(bytes) != -1) { byte[] message = bytes.array(); switch (message[0]) { case 1: { String nick = MessageUtils.parseMessage(message).first; if (!checkMessage(nick, "", clientSocket)) { continue; } if (clients.containsKey(nick) || nick.length() > 32) { if (nick.length() > 32) { sendMessage( clientSocket, MessageUtils.error("<server>: your nick is too long")); } else { sendMessage( clientSocket, MessageUtils.error("<server>: another user is using this nick")); } sendMessage(clientSocket, MessageUtils.bye()); anonymousClients.remove(clientSocket); Utils.tryClose(clientSocket); } else { System.out.println(nick + " enter this chatroom"); notifyAllClients(nick + " enter this chatroom"); sendMessage( clientSocket, MessageUtils.message("<server>", "Wellcome, your nick is " + nick)); anonymousClients.remove(clientSocket); clients.put(nick, clientSocket); } break; } case 2: { String nick = getNickFromSocket(clientSocket); if (nick == null) { Utils.printErrorAndExit("Error: it could not happen"); } Utils.Pair<String, String> pair = MessageUtils.parseMessage(message); if (!checkMessage(pair.first, pair.second, clientSocket)) { continue; } if (!pair.first.equals(nick)) { System.out.println("Cheater: " + nick); sendMessage(clientSocket, MessageUtils.message("<server>", "do not cheat")); } for (Entry<String, SocketChannel> client : clients.entrySet()) { if (!clientSocket.equals(client.getValue())) { sendMessage(client.getValue(), MessageUtils.message(nick, pair.second)); } } break; } case 3: disconnectClient(clientSocket); break; case 127: { String nick = getNickFromSocket(clientSocket); Utils.Pair<String, String> pair = MessageUtils.parseMessage(message); if (!checkMessage(pair.first, pair.second, clientSocket)) { continue; } if (!pair.first.equals(nick)) { System.out.println("Cheater: " + nick); sendMessage(clientSocket, MessageUtils.message("<server>", "do not cheat")); } System.out.println(nick + ": " + pair.second); break; } default: System.out.println("Bad message from " + getNickFromSocket(clientSocket)); sendMessage(clientSocket, MessageUtils.message("<server>", "bad message")); break; } } else { disconnectClient(clientSocket); } } } keys.clear(); } catch (Exception expt) { expt.printStackTrace(); Utils.printErrorAndExit(expt.getMessage()); } }
@Override public void run() { try { Scanner csvScan = new Scanner(csvFile); int count = 0; while (csvScan.hasNext()) { csvScan.nextLine(); count++; } csvScan.close(); csvScan = new Scanner(csvFile); for (int i = 0; i < count; i++) { progressBar.setValue(i * 100 / count); String data = csvScan.nextLine(), id = data.substring(1, data.indexOf('\'', 1)); if (frame.database.exist(id)) { if (mode == 0) { String[] option = {"覆盖", "合并", "忽略"}; mode = JOptionPane.showOptionDialog( Port.this, "请选择重复项处理方式", "遇到重复项", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, option, option[0]) + 1; } switch (mode) { case 1: frame.database.deletePic(frame.webServer, id); frame.database.delete(id); break; case 2: frame.database.merge(id, data); File picFile = new File(picDirectory.getPath() + "/" + id + ".jpg"); if (picFile.exists()) { frame.database.deletePic(frame.webServer, id); frame.database.update(id, "pic", "'" + frame.webServer.setPic(picFile) + "'"); } case 3: continue; } } frame.database.insert(data); File picFile = new File(picDirectory.getPath() + "/" + id + ".jpg"); if (picFile.exists()) frame.database.update(id, "pic", "'" + frame.webServer.setPic(picFile) + "'"); } csvScan.close(); frame.refresh(); progressBar.setValue(100); finish(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(Port.this, "导入失败!", "错误", JOptionPane.ERROR_MESSAGE); try { if (frame.database.exist("temp")) frame.database.delete("temp"); } catch (Exception e1) { } frame.refresh(); dispose(); } }