之前学习的一直都是javaweb,什么前端框架、SSM、nginx、数据库之类的,对于网络编程方面,我的了解可以说几乎为0。最近在工作中需要使用netty来实现一些内网通信的功能,这就比较尴尬了,瞬间感觉到这个世间充满了恶意,这不是专挑我的软肋下死手么?
上网找了一些netty的讲解和示例,理论部分半懂不懂,实际上手也是参照着示例写代码,这还真是“网络编程”呢,我笑了。
为了能学好这一块知识盲区,我决定从socket开始摸索,简单看了几篇文档,发现基础操作的话,似乎也不难,就想着先搞个极简版终端聊天练练手吧,为什么要搞终端聊天呢?(当然是因为不想学java的界面开发的知识),结果光速打脸了,这不应该呀?我这设想很美好,一个客户端、一个服务端,一边搞两个线程,一个线程负责发送数据,一个线程负责接收数据,至于接收数据的这个线程,怎么监听数据我不会搞,那就来个朴实无华又简单基础的循环加判断吧。然而,就是不能正常通信?
最终在查阅了几篇文档之后,找到了问题所在,由于我的io流方面的知识知之甚少,所以就很尴尬了,貌似是数据没过去... ...
代码如下(简单易懂且很菜,算是我自己备忘一下):
public class SendHandler implements Runnable { PrintWriter writer = null; public SendHandler(PrintWriter writer) { this.writer = writer; } @Override public void run() { Scanner scanner = new Scanner(System.in); while (true) { writer.println(scanner.nextLine()); } } }
以上是发送数据的处理器
public class ReciveHandler implements Runnable { BufferedReader reader = null; public ReciveHandler(BufferedReader reader) { this.reader = reader; } @Override public void run() { while (true) { try { System.out.println("RE:" + reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } } }
以上是接收数据的处理器
public class Client { public static ExecutorService pool = Executors.newFixedThreadPool(2); public static void main(String[] args) throws IOException { Socket socket = new Socket("0.0.0.0", 8089); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); send(writer); recive(reader); } public static void send(PrintWriter writer) { pool.execute(new SendHandler(writer)); } public static void recive(BufferedReader reader) { pool.execute(new ReciveHandler(reader)); } }
以上是客户端
public class Server { public static ExecutorService pool = Executors.newFixedThreadPool(2); public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8089); Socket socket = serverSocket.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); send(writer); recive(reader); } public static void send(PrintWriter writer) { pool.execute(new SendHandler(writer)); } public static void recive(BufferedReader reader) { pool.execute(new ReciveHandler(reader)); } }
以上是服务端
然后,就没有然后了...
如果有和我同样刚刚接触到这方面的小伙伴们觉得看不大懂(这几率应该比较小吧),那可以了解一下,线程池、io流、socket。
溜了溜了,菜鸟式离场... ...