1.问题:在学习Java的Socket编程,写了一些代码练习,但是又不知道是否规范,是否有优化的空间?2.代码: 1.问题:在学习Java的Socket编程,写了一些代码练习,但是又不知道是否规范,
1.问题:在学习Java的Socket编程,写了一些代码练习,但是又不知道是否规范,是否有优化的空间?2.代码:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394package com.nekolr.socket;import com.google.common.util.concurrent.ThreadFactoryBuilder;import java.io.*;import java.net.ServerSocket;import java.net.Socket;import java.util.concurrent.*;/** * @author nekolr */public class TcpSocket { static class TcpServer implements Runnable { private int port = 8888; @Override public void run() { try ( //创建服务端Socket,监听端口 ServerSocket serverSocket = new ServerSocket(port) ) { //打开监听,等待客户端的连接(在连接到来之前一直阻塞) Socket socket = serverSocket.accept(); try ( //获取输入流(获取客户端的消息) InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader reader = new BufferedReader(isr) ) { String line; while ((line = reader.readLine()) != null) { System.out.println("客户端" + socket.getInetAddress().getHostAddress() + "发送消息:" + line); } } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } static class TcpClient implements Runnable { private String host = "localhost"; private int port = 8888; @Override public void run() { try ( //创建客户端Socket,指定主机名和端口号 Socket socket = new Socket(host, port) ) { try ( //获取输出流(向服务端发送消息) OutputStream os = socket.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8"); BufferedWriter writer = new BufferedWriter(osw) ) { int i = 0; while (true) { i++; writer.write("hello" + i); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { TcpServer tcpServer = new TcpServer(); TcpClient tcpClient = new TcpClient(); ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("thread-pool").build(); ExecutorService executor = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(1024), factory, new ThreadPoolExecutor.AbortPolicy()); executor.execute(tcpServer); executor.execute(tcpClient); }}