Socket编程

来源:互联网 发布:什么租房软件最好 编辑:程序博客网 时间:2024/06/06 14:08

一 .多线程的SocketServer和SocketClient

1.ServerThread.java

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.Socket;/** */public class ServerThread implements Runnable{    Socket socket=null;    BufferedReader bufferedReader=null;    public ServerThread(Socket socket) {        this.socket = socket;        try {            bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));        } catch (IOException e) {            e.printStackTrace();        }    }    @Override    public void run() {        String content=null;        try {            while ((content=bufferedReader.readLine())!=null){                for (Socket iterable_element : MServerScoket.sockets) {PrintStream printStream=new PrintStream(socket.getOutputStream());printStream.println(content);}            }        } catch (IOException e) {        MServerScoket.sockets.remove(socket);            e.printStackTrace();        }    }}
2.ServerScoket.java

import java.io.IOException;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;import java.util.ArrayList;import java.util.List;public class MServerScoket {  public static List<Socket> sockets=new ArrayList<>();public static void main(String[] args) {// TODO Auto-generated method stub  try {            ServerSocket serverSocket=new ServerSocket(2536);            while(true){                Socket socket=serverSocket.accept();                sockets.add(socket);                new Thread(new ServerThread(socket)).start();            }        } catch (IOException e) {            e.printStackTrace();        }}}

3.ClientThread.java

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.Socket;public class ClientThread implements Runnable{Socket socket;BufferedReader bufferedReader;public ClientThread(Socket socket) {super();this.socket = socket;try {bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void run() {// TODO Auto-generated method stubString content;try {while((content=bufferedReader.readLine())!=null){System.out.println("客户端:"+content);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

4.
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.Socket;public class MScoketClient {public static void main(String[] args) {// TODO Auto-generated method stub Socket socket= null;        try {            socket = new Socket("127.0.0.1",2536);            new Thread(new ClientThread(socket)).start();            PrintStream printStream=new PrintStream(socket.getOutputStream());            BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));            String line;            while ((line=reader.readLine())!=null) {printStream.println(line);}        } catch (IOException e) {            e.printStackTrace();        }}}

二.非阻塞的Socket通信

1.NonBlockingServer.java

/** *  */package non.blocking;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.Channel;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.nio.charset.Charset;/** * @author Admin * */public class NonBlockingServer {private Selector selector=null;;private Charset charset=Charset.forName("utf-8");/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubtry {new NonBlockingServer().init();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void init() throws IOException {selector=Selector.open();ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();InetSocketAddress address=new InetSocketAddress("127.0.0.1",5679);serverSocketChannel.socket().bind(address);serverSocketChannel.configureBlocking(false);serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);while (selector.select()>0) {for (SelectionKey sKey : selector.selectedKeys()) {selector.selectedKeys().remove(sKey);if (sKey.isAcceptable()) {SocketChannel socketChannel=serverSocketChannel.accept();socketChannel.configureBlocking(false);socketChannel.register(selector,SelectionKey.OP_READ);sKey.interestOps(SelectionKey.OP_ACCEPT);}if (sKey.isReadable()) {SocketChannel socketChannel=(SocketChannel) sKey.channel();ByteBuffer buffer=ByteBuffer.allocate(1024);String content=null;try {while ((socketChannel.read(buffer))>0) {socketChannel.read(buffer);buffer.flip();content+=charset.decode(buffer);}System.out.println("socketChannel.read(buffer):"+content);sKey.interestOps(SelectionKey.OP_READ);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();sKey.cancel();if (sKey.channel()!=null) {sKey.channel().close();}if (content.length()>0) {for (SelectionKey key : selector.keys()) {Channel channel=key.channel();if (channel instanceof SocketChannel) {SocketChannel dest = (SocketChannel) channel;dest.write(buffer);}}}}}}}}}
2.NoBlockingClient.java

package non.blocking;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.SocketChannel;import java.nio.charset.Charset;import java.util.Scanner;public class NoBlockingClient {private Selector selector=null;private Charset charset=Charset.forName("utf-8");private SocketChannel sc=null;public static void main(String[] args) {// TODO Auto-generated method stubtry {new NoBlockingClient().init();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void init() throws IOException {selector=Selector.open();InetSocketAddress address=new InetSocketAddress("127.0.0.1", 5679);sc=SocketChannel.open(address);sc.configureBlocking(false);sc.register(selector, SelectionKey.OP_READ);new ClientThread().start();Scanner scanner=new Scanner(System.in);while (scanner.hasNextLine()) {sc.write(charset.encode(scanner.next()));}}class ClientThread extends Thread{@Overridepublic void run() {// TODO Auto-generated method stubtry {while (selector.select()>0) {for (SelectionKey key : selector.selectedKeys()) {selector.selectedKeys().remove(key);if (key.isReadable()) {SocketChannel socketChannel=(SocketChannel) key.channel();ByteBuffer buffer=ByteBuffer.allocate(1024);String content=null;while (socketChannel.read(buffer)>0) {socketChannel.read(buffer);buffer.flip();content+=charset.decode(buffer);}System.out.println("聊天信息:"+content);key.interestOps(SelectionKey.OP_READ);}}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}







0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 同学们,现布置讨论作业2:在自媒体高速发展的今天,每个人如何从自身做起,承担起一份网络社会的公共责任 在自媒体高速发展的今天,每个人如何从自身做起,承担起一份网络社会的公共责任?完成 交换机的级联端口与交换机的普通端口相连时,使用的双绞线跳线类型为( apfs转成exFAT 2004年江苏各市GDP排名 SRO(丝路传说)数据库解析 丝路传说 SRO_VT_SHARD_INIT 网贷 网贷数据 网贷数据出售 360彩 heml 黑暗之光 n0706 c语言入门 segmentwithsamestartandendpiont lte fan segmentwithsamestartandendpiont segmentwithsamestartandendpiont segmentwithsamestartandendpiont segmentwithsamestartandendpiont segmentwithsamestartandendpiont Windows10 Windows10cmd 简单描述你理解的Linux内核版本是什么?,发行版本是什么?CentOS与Linux是什么关系? 简单描述你理解的Linux内核版本? can\'tfindcompilerexecu 有的HTML标记名(标签名)都可以作为标签选择器。 OnenoteActiveX 菜鸟学黑客 不懂英语的菜鸟学黑客 http://150.109.21.127 http://150.109.21.127 国模私拍-最新精品乖巧小姐姐大尺度全裸诱惑掰穴玩弄私拍,水一直流摄影师都忍不住了 在窗口中添加其他组件和设置组件属性时需调用一些方法,其中,设置容器布局管理器的方法是(),添加其他组 183.199.111.214 300 300勇士