| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 /** | |
| 6 * Shows how to use Socket, ServerSocket and InputStream. | |
| 7 * | |
| 8 * (This deliberately sends data slowly, to show how InputStream can be | |
| 9 * read from asynchronously.) | |
| 10 */ | |
| 11 class SocketExample { | |
| 12 | |
| 13 int bytesSent = 0; | |
| 14 int bytesReceived = 0; | |
| 15 final int bytesTotal = 8; | |
| 16 final String host = "127.0.0.1"; | |
| 17 ServerSocket serverSocket; | |
| 18 Socket sendSocket; | |
| 19 Socket receiveSocket; | |
| 20 InputStream inputStream; | |
| 21 List receiveBuffer; | |
| 22 | |
| 23 SocketExample() { | |
| 24 // fixed size buffer we use to read from the InputStream | |
| 25 receiveBuffer = new List(4); | |
| 26 } | |
| 27 | |
| 28 void go() { | |
| 29 // initialize the server | |
| 30 serverSocket = new ServerSocket(host, 0, 5); | |
| 31 if (serverSocket == null) { | |
| 32 throw "can't get server socket"; | |
| 33 } | |
| 34 serverSocket.connectionHandler = onConnect; | |
| 35 print("accepting connections on ${host}:${serverSocket.port}"); | |
| 36 | |
| 37 // initialize the sender | |
| 38 sendSocket = new Socket(host, serverSocket.port); | |
| 39 if (sendSocket == null) { | |
| 40 throw "can't get send socket"; | |
| 41 } | |
| 42 | |
| 43 // send first 4 bytes immediately | |
| 44 for (int i = 0; i < 4; i++) { | |
| 45 sendByte(); | |
| 46 } | |
| 47 | |
| 48 // send next 4 bytes slowly | |
| 49 new Timer.repeating((Timer t) { | |
| 50 sendByte(); | |
| 51 if (bytesSent == bytesTotal) { | |
| 52 sendSocket.close(); | |
| 53 t.cancel(); | |
| 54 print("finished sending"); | |
| 55 } | |
| 56 }, 500); | |
| 57 } | |
| 58 | |
| 59 void onConnect(Socket connection) { | |
| 60 receiveSocket = connection; | |
| 61 inputStream = receiveSocket.inputStream; | |
| 62 inputStream.dataHandler = receiveBytes; | |
| 63 } | |
| 64 | |
| 65 void sendByte() { | |
| 66 sendSocket.writeList(const [65], 0, 1); | |
| 67 bytesSent++; | |
| 68 print("sending byte " + bytesSent.toString()); | |
| 69 } | |
| 70 | |
| 71 void receiveBytes() { | |
| 72 int numBytes = inputStream.readInto(receiveBuffer, 0, 4); | |
| 73 if (numBytes == 0) { | |
| 74 return; | |
| 75 } | |
| 76 | |
| 77 bytesReceived += numBytes; | |
| 78 print("received ${numBytes} bytes (${bytesReceived} bytes total)"); | |
| 79 if (bytesReceived >= bytesTotal) { | |
| 80 receiveSocket.close(); | |
| 81 serverSocket.close(); | |
| 82 print("done"); | |
| 83 } | |
| 84 } | |
| 85 } | |
| 86 | |
| 87 void main() => new SocketExample().go(); | |
| OLD | NEW |