blob: daf3a6c2fe89c7d77335d6405deb219eeacafd10 [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) {
danielp3c598e52013-02-24 06:12:54 +000056 LOG.severe("Socket read failed. Check your network configuration.");
57 Messages.severe("Socket read failed. Check your network configuration.");
danielp64c4e052013-02-23 07:21:41 +000058 return null;
59 }
60 return message;
61 }
62
63 /** Guarantees that large messages will be completely sent through a socket.
64 * @return Returns 0 for success, -1 for failure.
65 */
66 public static int sendAll(SocketChannel sock, ByteBuffer message) {
67 message.rewind();
68 while (message.remaining() > 0) {
69 try {
70 sock.write(message);
71 }
72 catch (IOException e) {
danielp3c598e52013-02-24 06:12:54 +000073 LOG.warning("Socket write failed. Check your network configuration.");
74 Messages.severe("Socket write failed. Check your network configuration.");
danielp64c4e052013-02-23 07:21:41 +000075 return -1;
76 }
77 }
78 return 0;
79 }
80
81 /** Overloaded method for sending a byte array. */
82 public static void sendAll(SocketChannel sock, byte[] message) {
83 ByteBuffer buff = ByteBuffer.wrap(message);
84 sendAll(sock, buff);
85 }
86
87 /** Overloaded method for sending a String. */
88 public static void sendAll(SocketChannel sock, String message) {
89 sendAll(sock, message.getBytes());
90 }
91}