JavaのSocketとThread
試行錯誤の残骸。
- テキストで行区切りで受信する毎に受信イベントが発生する
- イベントはlistenerで登録する
- 送信もMainスレッドと別で回せる
- Runnable interfaceに関数を詰めて渡せるのは便利だった
ClientSample.java
import java.io.*; import java.net.Socket; public class ClientSample{ public static void main(String args[]){ final LineSocketClient sock = new LineSocketClient("localhost", 8082); sock.onReceive(new OnReceiveListener(){ public void onReceive(String line){ System.out.println(line); } }); new Thread(new Runnable(){ public void run(){ int count = 0; while(true){ sock.send("count : " + count); try{ Thread.sleep(1000); } catch(Exception ex){ ex.printStackTrace(); } count++; } } }).start(); while(true){ System.out.println("--main loop--"); try{ Thread.sleep(1000); } catch(Exception ex){ ex.printStackTrace(); } } } }
LineSocketClient.java
import java.io.*; import java.net.Socket; public class LineSocketClient{ private Socket sock; private BufferedWriter bWriter; private BufferedReader bReader; private OnReceiveListener onReceiveListener; public LineSocketClient(String host, int port){ try{ this.sock = new Socket(host, port); this.bWriter = new BufferedWriter(new OutputStreamWriter(this.sock.getOutputStream())); this.bReader = new BufferedReader(new InputStreamReader(this.sock.getInputStream())); } catch(Exception ex){ ex.printStackTrace(); } } public void send(String data){ try{ bWriter.write(data); bWriter.flush(); } catch(Exception ex){ ex.printStackTrace(); } } public void onReceive(final OnReceiveListener onReceive){ new Thread(new Runnable(){ public void run(){ while(true){ try{ String line = bReader.readLine(); onReceive.onReceive(line); } catch(Exception ex){ ex.printStackTrace(); } } } }).start(); } }
OnReceiveListener.java
public interface OnReceiveListener{ public void onReceive(String received); }