---
title: "网络通信总结"
author: "raidyue"
date: "2012-10-28T15:33:16Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-10-28T15:32:55Z"
id: 1706781
url: "https://raidyue.iteye.com/blog/1706781"
---

网络通信：一句话说，用网络传输数据（各种数据） 。进行通讯那我们肯定需要知道传送到哪去，比如在现实中我们寄信，肯定需要知道目的地的地址，在计算机网络中我们就需要知道计算机的IP ，每个计算机拥有独立的IP ，这样我们就能把数据传送到我们需要的机器上，但是计算机上运行了那么多的程序我们怎么知道怎么区分他们呢? 因此我们用端口号区分我们计算机上的程序知道了IP 和端口号，我们就能对对应计算机上的对应程序发送数据，我们从最基础的文本消息开始传送。

      首先我们需要一个服务器和一个客户端，听上去很牛逼，其实也就几句代码搞定的事。

Java.net.ServerSocket server = new Java.net.ServerSocket(9393);

// 这样服务器就创建成功了，9393 代表他所绑定的端口号

Java.net.Socket client = server.accept();// 服务器会一直等待客户端连接

Java.net.Socket client = new java.net.Socket(“localhost”,9393);

// 客户端建立，localhost 表示本地连接，9393 表示连接的端口号

      启动我们创建的服务器和客户端就能让他们连接上，连接以后我们获取流来进行数据的传输

OutputStream out = client.getOutputStream();

InputStream in = client.getInputStream();

在正式进行数据传输之前我们还有一个很重要的事情要做，关于协议。协议不过是数据传输和数据接受的规定，就是服务器端按什么顺序传输数据，那么客户端就按什么顺序接受数据并处理。

比如我们实现一个简单的网络画板，客户端在画图形的同时，将坐标数据发送到服务器端，服务器端会同时出现相同的图形

```
// 显示画板窗体
	public void showMyFrame() {
		this.setTitle("client");
		this.setSize(600, 500);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(3);
		this.setResizable(false);
		// 添加图形选择面板
		GraphPanel gp = new GraphPanel();
		this.add(gp, BorderLayout.WEST);
		// 添加颜色选择面板
		ColorPanel cp = new ColorPanel();
		this.add(cp, BorderLayout.SOUTH);
		this.setVisible(true);
		g = this.getGraphics();
		client = sc.getClient();
                //监听器的添加
		MyListener ml = new MyListener(g, client, gp, cp);
		this.addMouseListener(ml);
	}
```

 在这个网络画板中使用的是自定义的简单通信协议，客户端按什么顺序发送消息服务器端就按相应的顺序处理消息，使用graphSign表示，不同类型的图形或者文件发送等，colorSign则表示发送的颜色，客户端就按照这个顺序发送数据

```
if (command.equals("line")) {
			g.drawLine(x1, y1, x2, y2);
			graphSign = 1;
			sendMsg(x1, y1, x2, y2);
		} else if (command.equals("rect")) {
			g.drawRect(Math.min(x2, x1), Math.min(y1, y2), Math.abs(x1 - x2),
					Math.abs(y1 - y2));
			graphSign = 2;
			sendMsg(x1, y1, x2, y2);
		} else if (command.equals("oval")) {
			g.drawOval(Math.min(x2, x1), Math.min(y1, y2),
					Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)),
					Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)));
			graphSign = 3;
			sendMsg(x1, y1, x2, y2);
		} // 向服务器发送坐标
	public void sendMsg(int x1, int y1, int x2, int y2) {
		try {
			// 输出流
			out = client.getOutputStream();
			dos = new DataOutputStream(out);
			dos.writeInt(graphSign);
			dos.writeInt(colorSign);
			dos.writeInt(x1);
			dos.writeInt(y1);
			dos.writeInt(x2);
			dos.writeInt(y2);
			dos.flush();
		} catch (Exception ef) {
			ef.printStackTrace();
		}
		System.out.println("向服务器发送： " + x1 + " " + y1 + " " + x2 + " " + y2);
	} 
```

 下面就是数据就收了，先接受标记，判断传送的是什么图形的标记

```
                                graphSign = dis.readInt();
				if (graphSign == 1) {
					drawLine(dis);
				} else if (graphSign == 2) {
					drawRect(dis);
				} else if (graphSign == 3) {
					drawOval(dis);
				} 
```

 接受到数据以后就画出对应的图形就大功告成了

 

Apache Mina初探

关于文件的引入

apache-mina-2.0.7\\dist\\ mina-core-2.0.7.jar

slf4j-1.7.2\\ slf4j-api-1.7.2.jar

slf4j-1.7.2\\slf4j-nop-1.7.2.jar

slf4j-1.7.2\\log4j-over-slf4j-1.7.2.jar

下载好以后从原文件夹中引入就好（反正我是这样做的）

 

客户端：

```
                NioSocketConnector connector = new NioSocketConnector();
		// 创建接受数据的过滤器
		DefaultIoFilterChainBuilder chain = connector.getFilterChain();
		// 设定该过滤器一行一行的读取数据
		chain.addLast("myChain", new ProtocolCodecFilter(
				new TextLineCodecFactory()));
		// 设定服务器端的消息处理器
		connector.setHandler(new ClientIoHandler());
		// 连接到服务器
		ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",
				9393));
		// waiting for connect
		cf.awaitUninterruptibly();
		cf.getSession().getCloseFuture().awaitUninterruptibly();
		connector.dispose();
```

 创建连接以后，使用IOHandler进行处理IoHandler抽象类下列方法，触发事件后调用

       sessionCreated()  sessionOpened()   sessionClosed()    sessionIdle()   exceptionCaught()               messageReceived()    messageSent

 

 

```
// 当一个客户端连接进入时
	public void sessionOpened(IoSession session) throws Exception {
		sessions.add(session);
		System.out.println("a new client:" + session.getRemoteAddress());
		System.out.println("the id is:" + session.getId());
	}

	// 当一个客户端关闭时
	public void sessionClosed(IoSession session) throws Exception {
		System.out.println("a client closed" + session.getRemoteAddress());
	}

	// 就收消息
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		String str = (String) message;
		System.out.println("message from client-->" + str);
		// 将最后一条消息发送后关闭 true-->直接关闭无需等待最后一条消息关闭
		if (str.equals("bye")) {
			session.close(true);
		}
       //客户端关闭
       public void sessionClosed(InSession session){

       }
        .............
```

 服务器端：

```
                // 使用NIO创建非阻塞的Server端Socket
		acceptor = new NioSocketAcceptor();
		// 创建接受数据的过滤器
		DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
		// 设定这个过滤器将一行一行的读取数据
		chain.addLast("myChain", new ProtocolCodecFilter(
				new TextLineCodecFactory()));
		// 设定服务器端的消息处理器，一个SimpleMinaServer对象
		acceptor.setHandler(new ServerIoHandler());
		// 设定服务器端口
		int port = 9393;
		// 绑定端口启动服务器
		acceptor.bind(new InetSocketAddress(port));
```

 

服务器端的IoHandler的用法与客户端的类似