⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dosender.java

📁 用java的net包写的一个小的点到点的聊天软件。用了2小时写的
💻 JAVA
字号:
package jsm;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;

import javax.swing.JOptionPane;

public class DoSender extends Thread {
	MessageHandler mh = MessageHandler.getMH();

	Message curm;

	Socket curs;

	BufferedWriter out;

	DoSender() {

	}

	public void run() {
		while (true) {
			synchronized (mh.sendingMS) {
				if (mh.sendingMS.isEmpty()) {
					try {
						
						mh.sendingMS.wait();

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				curm = (Message) mh.sendingMS.removeFirst();
			}
			doSend();
		}
	}

	public void doSend() {
		try {
			//每次建立一个Socket然后释放掉,这样很不好浪费网络资源
			curs = new Socket(curm.getDestination(), Receiver.PORT);
		} catch (IOException e) {
			//
			String ip = curm.getDestination().toString();
			int choice = JOptionPane.showConfirmDialog(null, "can't connect " + ip
					+ '\n' + "Do you want to retry", 
					"System message", 2,
					JOptionPane.QUESTION_MESSAGE);
			if (choice == JOptionPane.YES_OPTION) {
				mh.handleOutConnection(curm);
			} 
			return;
		}
		// try {
		// 设置了timeout后,一旦timeout事件发生就会抛出
		// InterruptedIOException应该进行合理的处理(通知用户)
		// curs.setSoTimeout(20000);
		// } catch (SocketException e) {

		// e.printStackTrace();
		// }
		System.out.println("get here");
		try {
			out = new BufferedWriter(
					new OutputStreamWriter(curs.getOutputStream()));
			out.write(curm.getSms(), 0, curm.getSms().length());
			out.flush();
		} catch (IOException e) {
			// maybe fail to getOutputStream()..I must do sth to handle it
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}

				if (curs != null) {
					curs.close();
				}
			} catch (IOException e) {

				e.printStackTrace();
			}
		}
	}

}

⌨️ 快捷键说明

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