serversend.java

来自「一个简易的java画图软件」· Java 代码 · 共 91 行

JAVA
91
字号
package net;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Iterator;
import app.Application;

import draw.figuare.AbstractFiguare;

/**
 * 服务器发送器
 */
public class ServerSend extends Thread {
	protected PaintServer owner;
	protected Socket socket;
	protected boolean isShutDown;

	protected Object obj;
	public String netName;

	public ServerSend(PaintServer owner, Socket socket, String netName) {
		this.owner = owner;
		this.socket = socket;
		this.netName = netName;
		obj = null;
		isShutDown = false;
	}

	/**
	 * 向客户端发送消息
	 * @param netMes 发送的消息
	 */
	public void sendMessage(NetMessage netMes) {
		synchronized (this) {
			this.obj = netMes;
			if (obj == null)
				isShutDown = true;
			notify();
		}
	}

	@Override
	public void run() {
		System.out.println(socket);
		try {
			ObjectOutputStream oos = new ObjectOutputStream(socket
					.getOutputStream());
			oos.writeObject(netName);

			// 初始化
			Iterator<AbstractFiguare> iter = owner.view.getCanvas()
					.getAllFiguares().iterator();
			while (iter.hasNext()) {
				AbstractFiguare fig = iter.next();
				oos
						.writeObject(new NetMessage(NetMessage.MES_NEW_FIGUARE,
								fig));
			}

			synchronized (this) {
				while (!isShutDown) {
					while (obj == null && !isShutDown) {
						try {
							wait();
						} catch (InterruptedException e2) {
							if (Application.DEBUG > 0)
								e2.printStackTrace();
						}
					}
					if (isShutDown)
						break;
					oos.writeObject(obj);
					obj = null;
				}
			}

			oos.close();
			socket.close();
			System.out.println("ServerSend End");
		} catch (SocketException e) {
			// 只是socket关闭的异常
		} catch (IOException e) {
			if (Application.DEBUG > 0)
				e.printStackTrace();
		}

	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?