Java基于Socket实现简单的多线程回显服务器功能示例
更新时间:2017年08月28日 10:27:08 作者:zwcwu31
这篇文章主要介绍了Java基于Socket实现简单的多线程回显服务器功能,结合实例形式分析了java使用socket进行多线程数据传输的相关操作技巧,需要的朋友可以参考下
本文实例讲述了Java基于Socket实现简单的多线程回显服务器功能。分享给大家供大家参考,具体如下:
需要两个类,一个是EchoServer,代表服务器。另外一个是EchoServerClient,代表客户端。代码如下:
package interview; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class EchoServer { public static void main(String []args) throws IOException{ ServerSocket server = new ServerSocket(6789); while(true){ Socket client = server.accept(); ClientHandler handler = new ClientHandler(client); new Thread(handler).start(); } } public static class ClientHandler implements Runnable{ private Socket client; @Override public void run() { InputStreamReader isr = null; try { isr = new InputStreamReader(client.getInputStream()); BufferedReader br = new BufferedReader(isr); PrintWriter pw = new PrintWriter(client.getOutputStream()); String msg = br.readLine(); System.out.println("收到" + client.getInetAddress() + "发送的" + msg); pw.println("收到了你发的" + msg); pw.flush(); } catch (IOException e) { e.printStackTrace(); } } public ClientHandler(Socket client){ this.client = client; } } }
下面是客户端代码:
package interview; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class EchoServerClient { public static void main(String []args) throws UnknownHostException, IOException{ Socket client = new Socket("127.0.0.1", 6789); Scanner sc = new Scanner(System.in); System.out.print("请输入要发送的内容:"); String msg = sc.nextLine(); sc.close(); PrintWriter pw = new PrintWriter(client.getOutputStream()); pw.println(msg); pw.flush(); InputStreamReader isr = new InputStreamReader(client.getInputStream()); BufferedReader br = new BufferedReader(isr); System.out.println("服务器返回:" + br.readLine()); client.close(); } }
NIO多路复用套接字方法如下:
package interview; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.util.Iterator; public class EchoServerNIO { private static ServerSocketChannel serverChannel = null; private static Selector selector = null;// 多路复用选择器 private static ByteBuffer buffer = null; // 缓冲区 public static void main(String []args) throws IOException{ init(); listen(); } static void init() throws IOException{ serverChannel = ServerSocketChannel.open(); buffer = ByteBuffer.allocate(1024); serverChannel.socket().bind(new InetSocketAddress(6789)); serverChannel.configureBlocking(false); selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); } static void listen() throws IOException{ while(true){ if(selector.select(5000) != 0){ Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while(it.hasNext()){ SelectionKey key = it.next(); it.remove(); handleKey(key); } } } } static void handleKey(SelectionKey key) throws IOException{ SocketChannel channel = null; if(key.isAcceptable()){ ServerSocketChannel serverChannel = (ServerSocketChannel)key.channel(); channel = serverChannel.accept(); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); }else if(key.isReadable()){ channel = (SocketChannel)key.channel(); buffer.clear(); if(channel.read(buffer) > 0){ buffer.flip(); CharBuffer charBuffer = CharsetHelper.decode(buffer); String msg = charBuffer.toString(); System.out.println("收到" + channel.getRemoteAddress() + "的消息:" + msg); channel.write(CharsetHelper.encode(CharBuffer.wrap("received your msg:" + msg))); } } } public static class CharsetHelper{ private static final String UTF_8 = "UTF-8"; private static CharsetEncoder encoder = Charset.forName(UTF_8).newEncoder(); private static CharsetDecoder decoder = Charset.forName(UTF_8).newDecoder(); private CharsetHelper() { } public static ByteBuffer encode(CharBuffer in) throws CharacterCodingException{ return encoder.encode(in); } public static CharBuffer decode(ByteBuffer in) throws CharacterCodingException{ return decoder.decode(in); } } }
更多关于java相关内容感兴趣的读者可查看本站专题:《Java Socket编程技巧总结》、《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
相关文章
Java异常处理中同时有finally和return语句的执行问题
这篇文章主要介绍了Java异常处理中同时有finally和return语句的执行问题,首先确定的是一般finally语句都会被执行...然后,需要的朋友可以参考下2015-11-11Java 8中Stream API的这些奇技淫巧!你Get了吗?
这篇文章主要介绍了Java 8中Stream API的这些奇技淫巧!你Get了吗?文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-08-08Java读取properties配置文件时,出现中文乱码的解决方法
下面小编就为大家带来一篇Java读取properties配置文件时,出现中文乱码的解决方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2016-11-11
最新评论