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

📄 serverbean.java

📁 用JAVA语言实现的UDPSocket通信的源代码!
💻 JAVA
字号:
package thread.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ServerBean {
	private DatagramSocket ds;

	private byte buffer[];

	private int clientport;

	private int serverport;

	private String content;

	private InetAddress ia;

	// 以下定义了Get和Set类型的方法
	/**
	 * @return the buffer
	 */
	public byte[] getBuffer() {
		return buffer;
	}

	/**
	 * @param buffer
	 *            the buffer to set
	 */
	public void setBuffer(byte[] buffer) {
		this.buffer = buffer;
	}

	/**
	 * @return the clientport
	 */
	public int getClientport() {
		return clientport;
	}

	/**
	 * @param clientport
	 *            the clientport to set
	 */
	public void setClientport(int clientport) {
		this.clientport = clientport;
	}

	/**
	 * @return the content
	 */
	public String getContent() {
		return content;
	}

	/**
	 * @param content
	 *            the content to set
	 */
	public void setContent(String content) {
		this.content = content;
	}

	/**
	 * @return the ds
	 */
	public DatagramSocket getDs() {
		return ds;
	}

	/**
	 * @param ds
	 *            the ds to set
	 */
	public void setDs(DatagramSocket ds) {
		this.ds = ds;
	}

	/**
	 * @return the ia
	 */
	public InetAddress getIa() {
		return ia;
	}

	/**
	 * @param ia
	 *            the ia to set
	 */
	public void setIa(InetAddress ia) {
		this.ia = ia;
	}

	/**
	 * @return the serverport
	 */
	public int getServerport() {
		return serverport;
	}

	/**
	 * @param serverport
	 * the serverport to set
	 */
	public void setServerport(int serverport) {
		this.serverport = serverport;
	}

	public ServerBean() throws SocketException, UnknownHostException {
		buffer = new byte[1024];
		clientport = 1985;
		serverport = 1986;
		content = "";
		ds = new DatagramSocket(serverport);
		ia = InetAddress.getByName("localhost");
	}

	public void listenClient() throws IOException {
		// 在循环体里接收消息
		while (true) {
			// 初始化DatagramPacket类型的变量
			DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
			// 接收消息,并把消息通过dp参数返回
			ds.receive(dp);
			content = new String(dp.getData(), 0, dp.getLength());
			// 打印消息
			print();
		}
	}

	public void print() {
		System.out.println(content);
	}

}

⌨️ 快捷键说明

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