private final void socketrun() { do { if (link.socketport != 0) { try { Socket socket = new Socket(InetAddress.getByName(getCodeBase().getHost()), link.socketport); socket.setSoTimeout(30000); socket.setTcpNoDelay(true); link.s = socket; } catch (Exception _ex) { link.s = null; } link.socketport = 0; } if (link.runme != null) { Thread thread = new Thread(link.runme); thread.setDaemon(true); thread.start(); link.runme = null; } if (link.iplookup != null) { String s = "unknown"; try { s = InetAddress.getByName(link.iplookup).getHostName(); } catch (Exception _ex) { } link.host = s; link.iplookup = null; } try { Thread.sleep(100L); } catch (Exception _ex) { } } while (true); }
/** * Connects to the remote machine by establishing a tunnel through a HTTP proxy with Basic * authentication. It issues a CONNECT request and authenticates with the HTTP proxy with Basic * protocol. * * @param address remote machine to connect to * @return a TCP/IP socket connected to the remote machine * @throws IOException if an I/O error occurs during handshake (a network problem) */ private Socket authenticateBasic(InetSocketAddress address, ConnectivitySettings cs) throws IOException { Socket proxy = new Socket(cs.getProxyHost(), cs.getProxyPort()); BufferedReader r = new BufferedReader( new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream()))); DataOutputStream dos = new DataOutputStream(proxy.getOutputStream()); String username = cs.getProxyUsername() == null ? "" : cs.getProxyUsername(); String password = cs.getProxyPassword() == null ? "" : String.valueOf(cs.getProxyPassword()); String credentials = username + ":" + password; String basicCookie = Base64Encoder.encode(credentials.getBytes("US-ASCII")); dos.writeBytes("CONNECT "); dos.writeBytes(address.getHostName() + ":" + address.getPort()); dos.writeBytes(" HTTP/1.0\r\n"); dos.writeBytes("Connection: Keep-Alive\r\n"); dos.writeBytes("Proxy-Authorization: Basic " + basicCookie + "\r\n"); dos.writeBytes("\r\n"); dos.flush(); String line = r.readLine(); if (sConnectionEstablishedPattern.matcher(line).find()) { for (; ; ) { line = r.readLine(); if (line.length() == 0) break; } return proxy; } throw new IOException("Basic authentication failed: " + line); }
public void run() { try { boolean connected = true; System.out.println("a client has connected!"); dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); while (connected) { int cid = clients.indexOf(this) + 1; try { String str = dis.readUTF(); System.out.println(str); for (int i = 0; i < clients.size(); i++) { clients.get(i).dos.writeUTF("Client" + cid + ":" + str); } } catch (IOException e) { connected = false; } } dis.close(); dos.close(); s.close(); clients.remove(this); System.out.println("a client is qiut!"); } catch (IOException e) { e.printStackTrace(); } }
/** * there is an issue with this method: if it is called often enough, the <CODE> * _s.sendUrgentData(0);</CODE> method that it invokes, will force the <CODE>_s</CODE> socket to * close on the other end, at least on Windows systems. This behavior is due to the fact that * OOB data handling is problematic since there are conflicting specifications in TCP. * Therefore, it is required that the method is not called with high frequency (see the <CODE> * PDBTExecSingleCltWrkInitSrv._CHECK_PERIOD_MSECS</CODE> flag in this file.) * * @return true iff the worker is available to accept work according to all evidence. */ private synchronized boolean getAvailability() { boolean res = _isAvail && _s != null && _s.isClosed() == false; if (res && _OK2SendOOB) { // work-around the OOB data issue // last test using OOB sending of data try { _OK2SendOOB = false; // indicates should not send OOB data until set to true _s.sendUrgentData(0); // unfortunately, if this method is called often enough, // it will cause the socket to close??? res = true; } catch (IOException e) { // e.printStackTrace(); utils.Messenger.getInstance() .msg("PDBTExecSingleCltWrkInitSrv.getAvailability(): Socket has been closed", 0); res = false; _isAvail = false; // declare availability to false as well // try graceful exit try { _s.shutdownOutput(); _s.close(); // Now we can close the Socket } catch (IOException e2) { // silently ignore } } } return res; }
public static ArrayList<Patient> getPatientList(Socket socket, ArrayList<Patient> patientList) { int id; String ic; String fname; String lname; int age; int cnumber; try { OutputStream output = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(output); InputStream input = socket.getInputStream(); DataInputStream dis = new DataInputStream(input); dos.writeInt(2); int numberOfPatients = dis.readInt(); for (int i = 0; i < numberOfPatients; i++) { id = dis.readInt(); ic = dis.readUTF(); fname = dis.readUTF(); lname = dis.readUTF(); age = dis.readInt(); cnumber = dis.readInt(); patientList.add(new Patient(id, ic, fname, lname, age, cnumber)); } } catch (IOException e) { System.out.println("Cannot get IO streams."); } return patientList; }
public static void main(String args[]) { int myport = 9090; Socket s; ServerSocket ss; BufferedReader fromSoc, fromKbd; PrintStream toSoc; String line, msg; try { s = new Socket("169.254.63.10", 6016); System.out.println("enter line"); System.out.println("connected"); toSoc = new PrintStream(s.getOutputStream()); toSoc.println(myport); String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=D://db.mdb; DriverID=22;READONLY=true;"; Connection con = DriverManager.getConnection(url, "", ""); Statement st = con.createStatement(); String ip = "169.254.63.10"; int port = 6016; String video = "rooney"; st.executeUpdate( " insert into p3 values('" + ip + "' , '" + port + "' , '" + video + "' ); "); fun(); } catch (Exception e) { System.out.println("exception" + e); } }
public static void main(String args[]) throws IOException { ServerSocket sSocket = new ServerSocket(sPort, 10); // Arguments Handling if (args.length != 1) { System.out.println("Must specify a file-path argument."); } else { String currentDir = System.getProperty("user.dir"); filePath = currentDir + "/src/srcFile/" + args[0]; filename = args[0]; } // Get list of chunks owned chunkOwned(); // Call FileSplitter FileSplitter fs = new FileSplitter(); fs.split(filePath); System.out.println("Waiting for connection"); while (true) { Socket connection = sSocket.accept(); System.out.println("Connection received from " + connection.getInetAddress().getHostName()); new Thread(new MultiThreadServer(connection)).start(); } }
public void run() { try { theInputStream = new BufferedReader(new InputStreamReader(client.getInputStream())); theOutputStream = new PrintStream(client.getOutputStream()); while (true) { readin = theInputStream.readLine(); chat.ta.append(readin + "\n"); } } catch (SocketException e) { chat.ta.append("连接中断!\n"); chat.clientBtn.setEnabled(true); chat.serverBtn.setEnabled(true); chat.tfaddress.setEnabled(true); chat.tfport.setEnabled(true); try { i--; skt.close(); client.close(); } catch (IOException err) { chat.ta.append(err.toString()); } } catch (IOException e) { chat.ta.append(e.toString()); } }
/** @return lines read from server. */ private static String[] getResponse(String clientId, String clientCommand, Socket server) throws IOException { try { /** Create filter I/O streams for the socket, Open our connection to server port . */ InputStreamReader inputStreamReader = new InputStreamReader(server.getInputStream()); BufferedReader fromServer = new BufferedReader(inputStreamReader); PrintStream toServer = new PrintStream(server.getOutputStream()); // Send machine name or IP address to server: toServer.println(clientId + " " + clientCommand); toServer.flush(); /** Read lines of response from the server,and block while synchronously waiting: */ final int lines = 2; String[] response = new String[lines]; for (int i = 0; i < lines; i++) { String textFromServer = fromServer.readLine(); response[i] = textFromServer; if (textFromServer == null) { throw new IOException("unable to read from server, end of the stream has been reached"); } else { System.out.println(textFromServer); } } return response; } catch (IOException x) { throw x; } }
private void server() { new CountDown(60).start(); while (true) { try { Socket socket = serverSock.accept(); System.out.println("New Client:" + socket); if (readyState[6] == 1) { System.out.println("正在游戏中,无法加入"); continue; } for (i = 0; i <= 5; i++) { if (players[i].equals("虚位以待")) break; } if (i > 5) { System.out.println("房间已满,无法加入"); continue; } i++; ObjectOutputStream remoteOut = new ObjectOutputStream(socket.getOutputStream()); clients.addElement(remoteOut); ObjectInputStream remoteIn = new ObjectInputStream(socket.getInputStream()); new ServerHelder(remoteIn, remoteOut, socket.getPort(), i).start(); } catch (IOException e) { System.out.println(e.getMessage() + ": Failed to connect to client."); try { serverSock.close(); } catch (IOException x) { System.out.println(e.getMessage() + ": Failed to close server socket."); } } } }
/** * serviceClient accepts a client connection and reads lines from the socket. Each line is handed * to executeCommand for parsing and execution. */ public void serviceClient() throws java.io.IOException { System.out.println("Accepting clients now"); Socket clientConnection = serverSocket.accept(); // Arrange to read input from the Socket InputStream inputStream = clientConnection.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); // Arrange to write result across Socket back to client OutputStream outputStream = clientConnection.getOutputStream(); PrintStream printStream = new PrintStream(outputStream); System.out.println( "Client acquired on port #" + serverSocket.getLocalPort() + ", reading from socket"); try { String commandLine; while ((commandLine = bufferedReader.readLine()) != null) { try { Float result = executeCommand(commandLine); // Only BALANCE command returns non-null if (result != null) { printStream.println(result); // Write it back to the client } } catch (ATMException atmex) { System.out.println("ERROR: " + atmex); } } } catch (SocketException sException) { // client has stopped sending commands. Exit gracefully. System.out.println("done"); } }
public static void main(String[] args) { String hostname; if (args.length > 0) { hostname = args[0]; } else { hostname = "tock.usno.navy.mil"; } try { Socket theSocket = new Socket(hostname, 13); InputStream timeStream = theSocket.getInputStream(); StringBuffer time = new StringBuffer(); int c; while ((c = timeStream.read()) != -1) time.append((char) c); String timeString = time.toString().trim(); System.out.println("It is " + timeString + " at " + hostname); } // end try catch (UnknownHostException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } } // end main
/** * Constructor, specifying the server host:port combination, login data and an output stream. * * @param host server name * @param port server port * @param user user name * @param pass password * @param output client output; if set to {@code null}, results will be returned as strings. * @throws IOException I/O exception */ public ClientSession( final String host, final int port, final String user, final String pass, final OutputStream output) throws IOException { super(output); ehost = host; socket = new Socket(); try { // limit timeout to five seconds socket.connect(new InetSocketAddress(host, port), 5000); } catch (final IllegalArgumentException ex) { throw new BaseXException(ex); } sin = socket.getInputStream(); // receive timestamp final BufferInput bi = new BufferInput(sin); final String ts = bi.readString(); // send user name and hashed password/timestamp sout = PrintOutput.get(socket.getOutputStream()); send(user); send(Token.md5(Token.md5(pass) + ts)); sout.flush(); // receive success flag if (!ok(bi)) throw new LoginException(); }
public void firstRun() throws Exception { Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/test.jsp" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); // Get the JSESSIONID from the response String line = null; while ((line = br.readLine()) != null) { System.out.println(line); if (line.startsWith("Set-Cookie:") || line.startsWith("Set-cookie:")) { break; } } if (line == null) { throw new Exception("Missing Set-Cookie response header"); } String jsessionId = getSessionIdFromCookie(line, JSESSIONID); // Store the JSESSIONID in a file FileOutputStream fos = new FileOutputStream(JSESSIONID); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(jsessionId); osw.close(); stat.addStatus(TEST_NAME, stat.PASS); }
public void secondRun() throws Exception { // Read the JSESSIONID from the previous run FileInputStream fis = new FileInputStream(JSESSIONID); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String jsessionId = br.readLine(); new File(JSESSIONID).delete(); Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/ResumeSession" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); String cookie = "Cookie: " + jsessionId + "\n"; os.write(cookie.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String line = null; boolean found = false; while ((line = br.readLine()) != null) { System.out.println(line); if (line.contains(EXPECTED_RESPONSE)) { found = true; break; } } if (found) { stat.addStatus(TEST_NAME, stat.PASS); } else { throw new Exception("Wrong response. Expected response: " + EXPECTED_RESPONSE + " not found"); } }
public static void main(String[] args) { try { System.out.println("Creando socket servidor"); ServerSocket serverSocket = new ServerSocket(); System.out.println("Realizando el enlace"); InetSocketAddress addr = new InetSocketAddress("localhost", 5555); serverSocket.bind(addr); System.out.println("Aceptando conexiones"); Socket newSocket = serverSocket.accept(); System.out.println("Conexión recibida"); InputStream is = newSocket.getInputStream(); OutputStream os = newSocket.getOutputStream(); byte[] mensaje = new byte[25]; is.read(mensaje); System.out.println("Mensaje recibido: " + new String(mensaje)); System.out.println("Cerrando el nuevo socket"); newSocket.close(); System.out.println("Cerrando el socket servidor"); serverSocket.close(); System.out.println("Terminado"); } catch (IOException e) { e.printStackTrace(); } }
// ********************************************************************************** // // 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); } }
/** Create the serversocket and use its stream to receive serialized objects */ public static void main(String args[]) { ServerSocket ser = null; Socket soc = null; String str = null; Date d = null; try { ser = new ServerSocket(8020); /* * This will wait for a connection to be made to this socket. */ soc = ser.accept(); InputStream o = soc.getInputStream(); ObjectInput s = new ObjectInputStream(o); str = (String) s.readObject(); d = (Date) s.readObject(); s.close(); // print out what we just received System.out.println(str); System.out.println(d); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println("Error during serialization"); System.exit(1); } }
public Server() { try { ServerSocket ss = new ServerSocket(SERVER_PORT); Socket s = ss.accept(); InputStream is = s.getInputStream(); OutputStream out = s.getOutputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String sss = br.readLine(); System.out.println(sss); PrintWriter pw = new PrintWriter(out); pw.print("hello,我是服务器。"); pw.close(); br.close(); isr.close(); out.close(); is.close(); s.close(); ss.close(); } catch (UnknownHostException ue) { ue.printStackTrace(); } catch (IOException oe) { oe.printStackTrace(); } }
public static void main(String args[]) { String fileToSend = "C:\\test1.txt"; while (true) { // Maak lokale variabels eerst aan. // Dit is nodig om deze ook te gebruiken buiten de "try catch" blok. ServerSocket welcomeSocket = null; Socket connectionSocket = null; BufferedOutputStream outToClient = null; try { // poort waar gebruiker kan op connecteren welcomeSocket = new ServerSocket(3248); // Tot er een gebruiker gevonden is zal .accept() blijven wachten // Nadat er iemand geconnecteerd is zal er een nieuwe socket aangemaakt worden waarmee deze // met elkaar communiceren connectionSocket = welcomeSocket.accept(); // buffer voor data communicatie tussen server en client outToClient = new BufferedOutputStream(connectionSocket.getOutputStream()); } catch (IOException ex) { System.out.println("IOException1"); } // if an I/O error occurs when opening the socket. if (outToClient != null) // wanneer buffer correct is aangemaakt zal deze niet een null waarde hebben { // gemaakte variabele doorgeven aan thread Connection c = new Connection(connectionSocket, outToClient, fileToSend); // thread starten c.start(); } } }
static void fun() { PrintStream toSoc; try { ServerSocket f = new ServerSocket(9090); while (true) { Socket t = f.accept(); BufferedReader fromSoc = new BufferedReader(new InputStreamReader(t.getInputStream())); String video = fromSoc.readLine(); System.out.println(video); searcher obj = new searcher(); boolean fs; fs = obj.search(video); if (fs == true) { System.out.println("stream will starts"); toSoc = new PrintStream(t.getOutputStream()); toSoc.println("stream starts"); } else { toSoc = new PrintStream(t.getOutputStream()); toSoc.println("sorry"); } } } catch (Exception e) { System.out.println(e); } }
/** Internal method. Connect to searchd, send request, get response as DataInputStream. */ private DataInputStream _DoRequest(int command, int version, ByteArrayOutputStream req) { /* connect */ Socket sock = _Connect(); if (sock == null) return null; /* send request */ byte[] reqBytes = req.toByteArray(); try { DataOutputStream sockDS = new DataOutputStream(sock.getOutputStream()); sockDS.writeShort(command); sockDS.writeShort(version); sockDS.writeInt(reqBytes.length); sockDS.write(reqBytes); } catch (Exception e) { _error = "network error: " + e; _connerror = true; return null; } /* get response */ byte[] response = _GetResponse(sock); if (response == null) return null; /* spawn that tampon */ return new DataInputStream(new ByteArrayInputStream(response)); }
/** Handshake with the debuggee */ void handshake(Socket s, long timeout) throws IOException { s.setSoTimeout((int) timeout); byte[] hello = "JDWP-Handshake".getBytes("UTF-8"); s.getOutputStream().write(hello); byte[] b = new byte[hello.length]; int received = 0; while (received < hello.length) { int n; try { n = s.getInputStream().read(b, received, hello.length - received); } catch (SocketTimeoutException x) { throw new IOException("handshake timeout"); } if (n < 0) { s.close(); throw new IOException("handshake failed - connection prematurally closed"); } received += n; } for (int i = 0; i < hello.length; i++) { if (b[i] != hello[i]) { throw new IOException("handshake failed - unrecognized message from target VM"); } } // disable read timeout s.setSoTimeout(0); }
public static void main(String[] args) { try { Socket s1 = new Socket("127.0.0.1", 57643); InputStream is = s1.getInputStream(); DataInputStream dis = new DataInputStream(is); System.out.println(dis.readUTF()); OutputStream os = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); dos.writeUTF("Oh my gosh..."); dis.close(); is.close(); dos.close(); os.close(); s1.close(); } catch (ConnectException connExc) { connExc.printStackTrace(); System.out.println("Server connection failed"); } catch (IOException ioExc) { ioExc.printStackTrace(); } }
private static void getMedicineList(Socket socket) { int medicineID; String medicineName; String medicineUnit; double price; try { OutputStream output = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(output); InputStream input = socket.getInputStream(); DataInputStream dis = new DataInputStream(input); dos.writeInt(8); int numberOfMedicine = dis.readInt(); for (int i = 0; i < numberOfMedicine; i++) { medicineID = dis.readInt(); medicineName = dis.readUTF(); medicineUnit = dis.readUTF(); price = dis.readDouble(); medicineList.add(new Medicine(medicineID, medicineName, medicineUnit, price)); } } catch (IOException e) { System.out.println("Cannot get IO streams."); } }
public static void main(String[] args) { String str; Socket sock = null; ObjectOutputStream writer = null; Scanner kb = new Scanner(System.in); try { sock = new Socket("127.0.0.1", 4445); } catch (IOException e) { System.out.println("Could not connect."); System.exit(-1); } try { writer = new ObjectOutputStream(sock.getOutputStream()); } catch (IOException e) { System.out.println("Could not create write object."); System.exit(-1); } str = kb.nextLine(); try { writer.writeObject(str); writer.flush(); } catch (IOException e) { System.out.println("Could not write to buffer"); System.exit(-1); } try { sock.close(); } catch (IOException e) { System.out.println("Could not close connection."); System.exit(-1); } System.out.println("Wrote and exited successfully"); }
private PDBTEW2Listener(PDBTExecSingleCltWrkInitSrv srv, Socket s) throws IOException { _srv = srv; _s = s; _ois = new ObjectInputStream(_s.getInputStream()); _oos = new ObjectOutputStream(_s.getOutputStream()); _oos.flush(); }
public String toString() { StringBuilder ret = new StringBuilder(); InetAddress local = null, remote = null; String local_str, remote_str; Socket tmp_sock = sock; if (tmp_sock == null) ret.append("<null socket>"); else { // since the sock variable gets set to null we want to make // make sure we make it through here without a nullpointer exception local = tmp_sock.getLocalAddress(); remote = tmp_sock.getInetAddress(); local_str = local != null ? Util.shortName(local) : "<null>"; remote_str = remote != null ? Util.shortName(remote) : "<null>"; ret.append( '<' + local_str + ':' + tmp_sock.getLocalPort() + " --> " + remote_str + ':' + tmp_sock.getPort() + "> (" + ((System.currentTimeMillis() - last_access) / 1000) + " secs old)"); } tmp_sock = null; return ret.toString(); }
public void run() { System.out.println("New Communication Thread Started"); try { PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; String[] inputTemp = new String[3]; while ((inputLine = in.readLine()) != null) { System.out.println("Server: " + inputLine); out.println(inputLine); if (inputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); } catch (IOException e) { System.err.println("Problem with Communication Server"); System.exit(1); } }
@Override public void run() { // System.out.println ("New Communication Thread Started"); try { BufferedReader in; // OUTPUT STREAM try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) { in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; // READ NUMBER OF FORTUNE COOKIES CLIENT WANTS while ((inputLine = in.readLine()) != null) { // System.out.println("Hello"); if (inputLine.equals("Bye.")) break; int number = Integer.parseInt(inputLine); System.out.println("Server: " + inputLine); // SENDS RANDOMLY GENERATED COOKIES out.println(new FortuneCookies().getCookies(number)); } } // CLIENT CLOSE in.close(); clientSocket.close(); } catch (IOException e) { System.err.println("Problem with Communication Server"); System.exit(1); } }