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

📄 udpsocketsender.java

📁 一个实用工具类
💻 JAVA
字号:
/* * Copyright (C) butor.com. All rights reserved. * * This software is published under the terms of the GNU Library General * Public License (GNU LGPL), a copy of which has been included with this * distribution in the LICENSE.txt file.  */package org.butor.net.udp.service;/** * ---------------------------------------------------------------- * 2000jun08,deb: Initial version */import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import org.butor.log.Log;/** *  * * @author  */public class UDPSocketSender {	public static final int DEFAULT_BUFFER_SIZE = 50;	public static final String NULL_MSG;	static {		char[] chrArray = new char[1];		chrArray[0] = '\0';		NULL_MSG = new String(chrArray);	}	protected DatagramSocket f_socket = null;	protected InetAddress f_host = null;	protected int f_udpPort = -1;	protected String f_hostName = null;	protected DatagramPacket f_packet = null;	protected String f_lastError = "";	/**	 * This method was created in VisualAge.	 * @return java.lang.String	 */	public String getLastErrorMsg() {		return f_lastError;	}	/**	 * DatagramSender constructor comment.	 */	public UDPSocketSender(String hostName, int udpPort) throws SocketException {		if (udpPort <= 0) {			throw new SocketException("Invalid UDP port: " + udpPort);		}		if ((null == hostName) || (hostName.length() <= 0)) {			Log.logStr(				this,				Log.LOG_TYPE_WARN,				"DatagramSender",				"Remote not specified, will use locahost");		}		f_udpPort = udpPort;		f_hostName = hostName;		try {			f_host = InetAddress.getByName(hostName);			f_socket = new DatagramSocket();			f_packet = new DatagramPacket(new byte[0], 0, f_host, f_udpPort);		} catch (java.net.UnknownHostException e) {			Log.logException(this, Log.LOG_TYPE_ERROR, "UDPSender", e);			f_lastError = e.getMessage();			throw new SocketException(f_lastError);		} catch (java.net.SocketException e) {			Log.logException(this, Log.LOG_TYPE_ERROR, "UDPSender", e);			f_lastError = e.getMessage();			throw new SocketException(f_lastError);		}	}	/**	 * This method was created in VisualAge.	 * @return boolean	 * @param msg java.lang.String	 */	public boolean send(String msg) {		int strLength = msg.length();		if ((null == msg) || (strLength <= 0)) {			Log.logStr(				this,				Log.LOG_TYPE_WARN,				"send()",				"Got NULL message to send! Sending on null char instead!");			msg = NULL_MSG;			strLength = msg.length();		}		byte[] buffer = msg.getBytes();		f_packet.setData(buffer);		f_packet.setLength(strLength);		try {			f_socket.send(f_packet);		} catch (java.io.IOException e) {			Log.logException(null, Log.LOG_TYPE_ERROR, "send()", e);			f_lastError = e.getMessage();			return false;		}		return true;	}}

⌨️ 快捷键说明

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