blob: e49a82b9177993d1d5a9f19caaa010f3feb7e7c3 [file] [log] [blame]
danielp64c4e052013-02-23 07:21:41 +00001/**
2 *
3 */
4package org.frc971;
5
6import java.io.IOException;
7
8import java.nio.ByteBuffer;
9import java.nio.channels.SocketChannel;
10import java.util.logging.Logger;
11
12/**
13 * @author daniel
14 * Socket operations used by other classes
15 */
16public class SocketCommon {
17
18 private final static Logger LOG = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
19
20 /** Reads on a SocketStream until it finds a given character sequence. */
21 public static String readtoBoundary(SocketChannel sock, String boundary) {
22 //reads from socket until it encounters a specific character combination
23 //if boundary is null, it reads until it runs out of data
24 ByteBuffer recvd = ByteBuffer.allocate(1024);
25 StringBuilder sb = new StringBuilder();
26 String message = "";
27 try {
28 int ret = 0;
29 while (ret != -1) {
30 ret = sock.read(recvd);
31 //System.out.println(ret);
32 if (ret == 0) {
33 //finished receiving
34 message = sb.toString();
35 if (boundary == null)
36 break;
37 }
38 else {
39 for (int i = 0; i < recvd.capacity() - recvd.remaining(); i++) {
40 sb.append((char)recvd.get(i));
41 }
42 recvd.clear();
43 if (boundary != null) {
44 if (sb.toString().contains(boundary)) {
45 message = sb.toString();
46 break;
47 }
48 else {
49 continue;
50 }
51 }
52 }
53 }
54 }
55 catch (IOException e) {
56 LOG.severe("Socket read failed.");
57 return null;
58 }
59 return message;
60 }
61
62 /** Guarantees that large messages will be completely sent through a socket.
63 * @return Returns 0 for success, -1 for failure.
64 */
65 public static int sendAll(SocketChannel sock, ByteBuffer message) {
66 message.rewind();
67 while (message.remaining() > 0) {
68 try {
69 sock.write(message);
70 }
71 catch (IOException e) {
72 LOG.warning("Socket write failed.");
73 return -1;
74 }
75 }
76 return 0;
77 }
78
79 /** Overloaded method for sending a byte array. */
80 public static void sendAll(SocketChannel sock, byte[] message) {
81 ByteBuffer buff = ByteBuffer.wrap(message);
82 sendAll(sock, buff);
83 }
84
85 /** Overloaded method for sending a String. */
86 public static void sendAll(SocketChannel sock, String message) {
87 sendAll(sock, message.getBytes());
88 }
89}