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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | //package test; import java.io.BufferedOutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; class SocketClient { private String address = "127.0.0.1";// 連線的IP private int port = 8769;// 連線的port public SocketClient(String data) { Socket client = new Socket(); InetSocketAddress isa = new InetSocketAddress(this.address, this.port); try { client.connect(isa, 10000); BufferedOutputStream out = new BufferedOutputStream(client .getOutputStream()); // 送出字串 out.write(data.getBytes()); out.flush(); out.close(); out = null; client.close(); client = null; System.out.println(data); } catch (java.io.IOException e) { System.out.println("Socket連線有問題 !"); System.out.println("IOException :" + e.toString()); } } } public class SocketServer extends java.lang.Thread { private boolean OutServer = false; private ServerSocket server; private final int ServerPort = 8769;// 要監控的port public SocketServer() { try { server = new ServerSocket(ServerPort); } catch (java.io.IOException e) { System.out.println("Socket啟動有問題 !"); System.out.println("IOException :" + e.toString()); } } public void run() { Socket socket; java.io.BufferedInputStream in; System.out.println("伺服器已啟動 !"); while (!OutServer) { socket = null; try { synchronized (server) { socket = server.accept(); } System.out.println("取得連線 : InetAddress = " + socket.getInetAddress()); // TimeOut時間 socket.setSoTimeout(15000); in = new java.io.BufferedInputStream(socket.getInputStream()); byte[] b = new byte[1024]; String data = ""; int length; while ((length = in.read(b)) > 0)// <=0的話就是結束了 { data += new String(b, 0, length); } System.out.println("我取得的值:" + data); new SocketClient(data); in.close(); in = null; socket.close(); } catch (java.io.IOException e) { System.out.println("Socket連線有問題 !"); System.out.println("IOException :" + e.toString()); } } } public static void main(String args[]) { (new SocketServer()).start(); //new SocketClient("receive!!"); } } |
Direct link: https://paste.plurk.com/show/588009