public Cliente(Socket s) { super("OPERACIONES CON BD"); socket = s; try { salida = new DataOutputStream(socket.getOutputStream()); inObjeto = new ObjectInputStream(socket.getInputStream()); } catch (IOException e) { e.printStackTrace(); System.exit(0); } setLayout(null); etiqueta.setBounds(10, 10, 200, 30); add(etiqueta); empconsultar.setBounds(210, 10, 50, 30); add(empconsultar); textarea1 = new JTextArea(); scrollpane1 = new JScrollPane(textarea1); scrollpane1.setBounds(10, 50, 400, 300); add(scrollpane1); boton.setBounds(420, 10, 100, 30); add(boton); desconectar.setBounds(420, 50, 100, 30); add(desconectar); textarea1.setEditable(false); boton.addActionListener(this); desconectar.addActionListener(this); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); }
/** Start talking to the server */ public void start() { String codehost = getCodeBase().getHost(); if (socket == null) { try { // Open the socket to the server socket = new Socket(codehost, port); // Create output stream out = new ObjectOutputStream(socket.getOutputStream()); out.flush(); // Create input stream and start background // thread to read data from the server in = new ObjectInputStream(socket.getInputStream()); new Thread(this).start(); } catch (Exception e) { // Exceptions here are unexpected, but we can't // really do anything (so just write it to stdout // in case someone cares and then ignore it) System.out.println("Exception! " + e.toString()); e.printStackTrace(); setErrorStatus(STATUS_NOCONNECT); socket = null; } } else { // Already started } if (socket != null) { // Make sure the right buttons are enabled start_button.setEnabled(false); stop_button.setEnabled(true); setStatus(STATUS_ACTIVE); } }
// ********************************************************************************** // // Theoretically, you shouldn't have to alter anything below this point in this file // unless you want to change the color of your agent // // ********************************************************************************** public void getConnected(String args[]) { try { // initial connection int port = 3000 + Integer.parseInt(args[1]); s = new Socket(args[0], port); sout = new PrintWriter(s.getOutputStream(), true); sin = new BufferedReader(new InputStreamReader(s.getInputStream())); // read in the map of the world numNodes = Integer.parseInt(sin.readLine()); int i, j; for (i = 0; i < numNodes; i++) { world[i] = new node(); String[] buf = sin.readLine().split(" "); world[i].posx = Double.valueOf(buf[0]); world[i].posy = Double.valueOf(buf[1]); world[i].numLinks = Integer.parseInt(buf[2]); // System.out.println(world[i].posx + ", " + world[i].posy); for (j = 0; j < 4; j++) { if (j < world[i].numLinks) { world[i].links[j] = Integer.parseInt(buf[3 + j]); // System.out.println("Linked to: " + world[i].links[j]); } else world[i].links[j] = -1; } } currentNode = Integer.parseInt(sin.readLine()); String myinfo = args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink // send the agents name and color sout.println(myinfo); } catch (IOException e) { System.out.println(e); } }
/** * ** Writes the specified byte array to the specified socket's output stream ** @param socket The * socket which's output stream to write to ** @param b The byte array to write to the socket * output stream ** @throws IOException if an error occurs */ protected static void socketWriteBytes(Socket socket, byte b[]) throws IOException { if ((socket != null) && (b != null)) { OutputStream output = socket.getOutputStream(); output.write(b); output.flush(); } }
public void setUpNetworking() { try { Socket sock = new Socket("192.168.0.117", 5555); PrintWriter writer = new PrintWriter(sock.getOutputStream()); System.out.println("networking established"); } catch (IOException ex) { ex.printStackTrace(); } }
/** * ** Writes <code>length</code> bytes from the specified byte array ** starting at <code>offset * </code> to the specified socket's output stream. ** @param socket The socket which's output * stream to write to ** @param b The byte array to write to the socket output stream ** @param * offset The start offset in the data to begin writing at ** @param length The length of the * data. Normally <code>b.length</code> ** @throws IOException if an error occurs */ protected static void socketWriteBytes(Socket socket, byte b[], int offset, int length) throws IOException { if ((socket != null) && (b != null)) { int bofs = offset; int blen = (length >= 0) ? length : b.length; OutputStream output = socket.getOutputStream(); output.write(b, bofs, blen); output.flush(); } }
public ServerAgentThread(Server father, Socket sc) { this.father = father; this.sc = sc; try { din = new DataInputStream(sc.getInputStream()); dout = new DataOutputStream(sc.getOutputStream()); } catch (Exception e) { e.printStackTrace(); } }
// メッセージをサーバーに送信する public void sendMessage(String msg) { try { OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output); writer.println(msg); writer.flush(); } catch (Exception err) { msgTextArea.append("ERROR>" + err + "\n"); } }
public void connect() { try { s = new Socket("127.0.0.1", 8888); dos = new DataOutputStream(s.getOutputStream()); System.out.println("connected!"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
// 서버와 연결 public void connection() { try { s = new Socket("localhost", 65535); // s=>server in = new BufferedReader(new InputStreamReader(s.getInputStream())); // 서버로 값을 읽어들임 out = s.getOutputStream(); // 서버로 값을 보냄 /*out.write((Function.LOGIN+"|"+id+"|" +pass+"\n").getBytes());*/ } catch (Exception ex) { } new Thread(this).start(); // run()으로 이동 // 서버로부터 응답값을 받아서 처리 }
public Client(int port) { Socket socket = null; try { socket = new Socket("127.0.0.1", port); chatField.setText("------CONNECTION ESTABLISHED------"); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); enableChat(); } catch (Exception e) { chatField.setText("Connection Failed"); } }
public Server(int port) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); clientSocket = serverSocket.accept(); chatField.setText("------CONNECTION ESTABLISHED------"); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); enableChat(); } catch (IOException e) { chatField.setText("Connection Fail"); } }
/** * run will be exicuted when the thread is called, and will connect to the server and start * communicating with it. */ public void run() { WaitForConnection wfc = new WaitForConnection("Waiting For Connection"); m_OldWindow.setEnabled(false); try { m_Socket = new Socket(m_IP, m_Port); // System.out.println("Connecting to ChatService..."); m_ChatSocket = new Socket(m_IP, m_Port); // System.out.println("\nConnected to ChatService..."); wfc.updateMessage("Waiting For Other Players"); // System.out.println("Getting OutputStream Stream From server..."); toServer = new ObjectOutputStream(m_Socket.getOutputStream()); toChatServer = new ObjectOutputStream(m_ChatSocket.getOutputStream()); toChatServer.flush(); // System.out.println("Getting Input Stream From server..."); fromServer = new ObjectInputStream(m_Socket.getInputStream()); fromChatServer = new ObjectInputStream(m_ChatSocket.getInputStream()); m_ChatService = new ChatService(); m_ChatServiceThread = new Thread(m_ChatService); m_ChatServiceThread.start(); m_MultiPlayerMenu.startGame(); wfc.dispose(); m_OldWindow.dispose(); } catch (java.net.ConnectException e) { wfc.dispose(); MenuWindow menu = new MenuWindow(new JFrame("")); JOptionPane.showMessageDialog(menu.getMainFrame(), "Error Connection refused"); m_OldWindow.setEnabled(true); } catch (IOException ex) { System.err.print(ex); } }
public void connect(String user, String pass) { if (!connected) { try { socket = new Socket(domain, 4446); out = new PrintWriter(socket.getOutputStream(), true); // in = new BufferedReader(new InputStreamReader(socket.getInputStream())); in = new ObjectInputStream(socket.getInputStream()); } catch (java.net.UnknownHostException e) { System.err.println("Don't know about host"); return; } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to"); return; } this.connected = true; rec = new Receiver(in); rec.start(); } }
@Override public void run() { // TODO Auto-generated method stub try { Socket s = new Socket(hostin, portin); InputStream ins = s.getInputStream(); OutputStream os = s.getOutputStream(); ir = new BufferedReader(new InputStreamReader(ins)); pw = new PrintWriter(new OutputStreamWriter(os), true); pw.print(nick); while (true) { String line = ir.readLine(); jta.append(line + "\n"); jsp.getVerticalScrollBar().setValue(jsp.getVerticalScrollBar().getMaximum()); } } catch (IOException e) { e.printStackTrace(); } }
public void launchChess() { mainWindow = new JFrame("网络黑白棋 作者:张炀"); jpWest = new JPanel(); jpEast = new JPanel(); jpNorth = new JPanel(); jpSouth = new JPanel(); jpCenter = new JPanel(); turnLabel = new JLabel(); blackNumberLabel = new JLabel("黑棋:\n" + black + " "); whiteNumberLabel = new JLabel("白棋:\n" + white + " "); timeLabel = new JLabel("时间: " + time + " s"); noticeLabel = new JLabel(); noticeLabel = new JLabel("请选择:"); numberPane = new JPanel(); readyPane = new JPanel(); jt1 = new JTextField(18); // 发送信息框 jt2 = new JTextArea(3, 30); // 显示信息框 js = new JScrollPane(jt2); jt2.setLineWrap(true); jt2.setEditable(false); // jt1.setLineWrap(true); send = new JButton("发送"); cancel = new JButton("取消"); regret = new JButton("悔棋"); submit = new JButton("退出"); begin = new JButton("开始"); save = new JButton("存盘"); save.setEnabled(true); begin.setEnabled(true); fighter = new JRadioButton("下棋"); audience = new JRadioButton("观看"); group = new ButtonGroup(); group.add(audience); group.add(fighter); group.add(AIPlayer); submit.addActionListener(this); begin.addActionListener(this); save.addActionListener(this); send.addActionListener(this); cancel.addActionListener(this); regret.addActionListener(this); fighter.addActionListener(this); audience.addActionListener(this); jpNorth.setLayout(new BorderLayout()); jpNorth.add(turnLabel, BorderLayout.NORTH); jpNorth.add(jpCenter, BorderLayout.CENTER); jpSouth.add(js); jpSouth.add(jt1); jpSouth.add(send); jpSouth.add(cancel); jpEast.setLayout(new GridLayout(3, 1)); submit.setBackground(new Color(130, 251, 241)); panel x = new panel(); jpEast.add(x); jpEast.add(numberPane); jpEast.add(readyPane); numberPane.add(blackNumberLabel); numberPane.add(whiteNumberLabel); numberPane.add(timeLabel); numberPane.add(submit); numberPane.add(begin); numberPane.add(save); numberPane.add(regret); readyPane.add(noticeLabel); readyPane.add(fighter); readyPane.add(audience); // readyPane.add(save); // readyPane.add(regret); jpCenter.setSize(400, 400); jmb = new JMenuBar(); document = new JMenu("游戏 "); edit = new JMenu("设置 "); insert = new JMenu("棋盘 "); help = new JMenu("帮助 "); jmb.add(document); jmb.add(edit); jmb.add(insert); jmb.add(help); // mainWindow.setJMenuBar(jmb); mainWindow.setBounds(80, 80, 600, 600); mainWindow.setResizable(false); jsLeft = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, jpNorth, jpSouth); jsBase = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, jsLeft, jpEast); mainWindow.add(jsBase); mainWindow.setVisible(true); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jsBase.setDividerLocation(0.7); jsLeft.setDividerLocation(0.78); jpCenter.setLayout(new GridLayout(8, 8, 0, 0)); ImageIcon key = new ImageIcon("chess1.jpg"); for (int i = 0; i < cell.length; i++) for (int j = 0; j < cell.length; j++) { cell[i][j] = new ChessBoard(i, j); cell[i][j].addMouseListener(this); jpCenter.add(cell[i][j]); } cell[3][3].state = cell[4][4].state = '黑'; cell[4][3].state = cell[3][4].state = '白'; cell[3][3].taken = cell[4][4].taken = true; cell[4][3].taken = cell[3][4].taken = true; RememberState(); new Thread(new TurnLabel(this)).start(); file = new File("D:/" + myRole); try { fout = new FileOutputStream(file); out = new ObjectOutputStream(fout); } catch (IOException e1) { e1.printStackTrace(); } Connect(); try { out99 = new ObjectOutputStream(socket99.getOutputStream()); in99 = new ObjectInputStream(socket99.getInputStream()); out66 = new ObjectOutputStream(socket66.getOutputStream()); in66 = new ObjectInputStream(socket66.getInputStream()); out88 = new DataOutputStream(socket88.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } new Thread(new Client9999(this)).start(); new Thread(new Client6666(this)).start(); }
public void send(String str) throws IOException { DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF(str); }
@Override public void run() { try { // Create data input and output streams DataInputStream inputFromClient = new DataInputStream(socket.getInputStream()); DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream()); // Set up a byte buffer to capture the file from the client byte[] buffer = new byte[BUFFER_SIZE]; OutputStream outputStream = null; String fileName = ""; boolean createFile = true; int bytesReceived = 0; long totalBytesReceived = 0; long fileSize = 0; // Continuously serve the client while (true) { bytesReceived = inputFromClient.read(buffer); if (bytesReceived > 0) { // Get the file transmission header from the initial client packet String transmitHeader = new String(buffer, 0, bytesReceived); // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().; String[] header = transmitHeader.split(HEADER_DEL); fileSize = Long.parseLong(header[0]); fileName = header[1]; // Send receipt acknowledgment back to the client. Just send back the number of bytes // received. outputToClient.writeInt(bytesReceived); // Reinitialize buffer values buffer = new byte[BUFFER_SIZE]; bytesReceived = 0; } // Wait for client to send bytes while ((bytesReceived = inputFromClient.read(buffer)) != -1) { if (inputFromClient.available() > 0) { if (createFile) { // Get a unique name for the file to be received fileName = textFolder.getText() + fileName; // getUniqueFileName(); outputStream = createFile(fileName); createFile = false; textArea.append("Receiving file from client.\n"); } // Write bytes to file outputStream.write(buffer, 0, bytesReceived); } else { // We get here if no more data is available, but some bytes were already // received // If bytes were received and the file wasn't already created, // it means that the file was smaller than our buffer size. // Create the file... if (bytesReceived > 0 && createFile) { // Get a unique name for the file to be received fileName = textFolder.getText() + fileName; // getUniqueFileName(); outputStream = createFile(fileName); createFile = false; textArea.append("Receiving file from client.\n"); } if (outputStream != null) { if (bytesReceived > 0) { // Write remaining bytes to file, if any outputStream.write(buffer, 0, bytesReceived); } outputStream.flush(); outputStream.close(); textArea.append("Received file successfully. Saved as " + fileName + "\n"); // Return success to client. outputToClient.writeInt(0); } // Reset creation flag createFile = true; break; } // Reinitialize buffer values buffer = new byte[BUFFER_SIZE]; bytesReceived = 0; } } } catch (IOException e) { System.err.println(e); } }
public void actionPerformed(ActionEvent e) { Object source = e.getSource(); // Client pressed enter in the message entry field-send it if (source == enterField) { // Get the message message = e.getActionCommand(); try { // Encipher the message if (message.length() > plaintextBlockSize) message = message.substring(0, plaintextBlockSize); byte[] ciphertext = Ciphers.RSAEncipherWSalt(message.getBytes(), BigIntegerMath.THREE, recipModulus, sr); // Send to the server output.write(ciphertext); output.flush(); // Display same message in client output area displayArea.append("\n" + message); enterField.setText(""); } catch (IOException ioe) { displayArea.append("\nError writing message"); } } else if (source == connectButton) { if (connection != null) { // Already connected-button press now means disconnect try { // Send final message of 0 byte[] lastMsg = new byte[1]; lastMsg[0] = 0; output.write(Ciphers.RSAEncipherWSalt(lastMsg, BigIntegerMath.THREE, recipModulus, sr)); output.flush(); // close connection and IO streams, change some components closeAll(); } catch (IOException ioe) { displayArea.append("\nError closing connection"); } } else { // Not connected-connect // Get name of server to connect to chatServer = serverField.getText(); displayArea.setText("Attempting connection to " + chatServer); try { // Set up the socket connection = new Socket(chatServer, 55555); displayArea.append("\nConnected to: " + connection.getInetAddress().getHostName()); // Set up the IO streams output = new DataOutputStream(connection.getOutputStream()); output.flush(); input = new DataInputStream(connection.getInputStream()); // Exchange public keys with the server-send yours, get theirs exchangeKeys(); // Change appearance/functionality of some components serverField.setEditable(false); connectButton.setLabel("Disconnect from server above"); enterField.setEnabled(true); // Set up a thread to listen for the connection listener = new Thread( new Runnable() { public void run() { go(); } }); listener.start(); } catch (IOException ioe) { displayArea.append("\nError connecting to " + chatServer); } } } }
// The main procedure public static void main(String args[]) { String s; initGUI(); while (true) { try { // Poll every ~10 ms Thread.sleep(10); } catch (InterruptedException e) { } switch (connectionStatus) { case BEGIN_CONNECT: try { // Try to set up a server if host if (isHost) { hostServer = new ServerSocket(port); socket = hostServer.accept(); } // If guest, try to connect to the server else { socket = new Socket(hostIP, port); } in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); changeStatusTS(CONNECTED, true); } // If error, clean up and output an error message catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; case CONNECTED: try { // Send data if (toSend.length() != 0) { out.print(toSend); out.flush(); toSend.setLength(0); changeStatusTS(NULL, true); } // Receive data if (in.ready()) { s = in.readLine(); if ((s != null) && (s.length() != 0)) { // Check if it is the end of a trasmission if (s.equals(END_CHAT_SESSION)) { changeStatusTS(DISCONNECTING, true); } // Otherwise, receive what text else { appendToChatBox("INCOMING: " + s + "\n"); changeStatusTS(NULL, true); } } } } catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; case DISCONNECTING: // Tell other chatter to disconnect as well out.print(END_CHAT_SESSION); out.flush(); // Clean up (close all streams/sockets) cleanUp(); changeStatusTS(DISCONNECTED, true); break; default: break; // do nothing } } }
// set up streams private void setupStreams() throws IOException { output = new ObjectOutputStream(connection.getOutputStream()); output.flush(); input = new ObjectInputStream(connection.getInputStream()); showMessage("\n Streams set up \n"); }
/** * Class that contains the main function which creates the window for the game and implements the * server/client socket */ @SuppressWarnings("deprecation") public static void main(String args[]) { int i = -1; // Variable to keep track of the result from the game do // Do-while loop { try { JFrame frame = getFrame(); // Create the frame // Dialog to get the name from the player as string, put the string in a label String sname = returnNameString(); JLabel label = new JLabel(sname); // Create the status bar panel and shove it down the bottom of the frame JPanel statusPanel = new JPanel(); statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED)); statusPanel.setBackground(Color.red); frame.add(statusPanel, BorderLayout.SOUTH); // Create a label, placed at the bottom of the frame JLabel statusLabel = new JLabel(); statusLabel.setHorizontalAlignment(SwingConstants.LEFT); statusPanel.add(statusLabel); Button clearButton = new Button("Clear"); // Creating a "clear" button clearButton.setSize(new Dimension(10, 20)); statusPanel.add(label); statusPanel.add(clearButton); // Adding the button to the panel statusPanel.add(getTime()); // Adding the clock to the status panel frame.setVisible(true); char ch; if (args.length == 0) ch = 'O'; else ch = 'X'; TicTacPanel ticTacPanel = new TicTacPanel(ch); // Create a panel for the game TicTacAction ticTacAction = new TicTacAction(ticTacPanel); // Handle actions in the game clearButton.addActionListener(ticTacAction); ticTacPanel.addMouseListener(ticTacAction); frame.add(ticTacPanel); frame.show(); // Creating socket and I/O stream objects Socket s; ObjectOutputStream oops; ObjectInputStream oips; switch (ch) { case 'O': s = (new ServerSocket(7777)).accept(); oops = new ObjectOutputStream(s.getOutputStream()); oops.writeObject(ticTacPanel.ttt); ticTacAction.ready = false; break; case 'X': default: s = new Socket(args[0], 7777); ticTacAction.ready = true; } while (true) // Infinite loop { oips = new ObjectInputStream(s.getInputStream()); ticTacPanel.ttt = (TicTacGame) (oips.readObject()); ticTacPanel.paint(ticTacPanel.getGraphics()); ticTacAction.ready = true; while (ticTacAction.ready) { Thread.sleep(100); } oops = new ObjectOutputStream(s.getOutputStream()); oops.writeObject(ticTacPanel.ttt); i = ticTacPanel.ttt.checkWin(); // Check if there's a winner if (i == 1) // A winner is declared { TicTacPanel.infoBox("The winner is " + sname + "!", "Game Over"); ticTacPanel.ttt.clearAll(); ticTacPanel.paint(ticTacPanel.getGraphics()); } else if (i == 0) // No winner, but every square is covered so the game is done { TicTacPanel.infoBox("We have a tie!", "Game Over"); ticTacPanel.ttt.clearAll(); ticTacPanel.paint(ticTacPanel.getGraphics()); } } } catch (Exception e) { System.out.println(e); e.printStackTrace(); System.exit(1); } } while (i == -1); // End of do-while loop }