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

📄 udpserver.java

📁 UDP一对一通信
💻 JAVA
字号:
import java.io.*;
import java.net.*;
public class udpserver
{
	static public void main(String[] args) throws IOException
	{
		DatagramSocket svrsoc=null;//服务器接收的socket
		DatagramSocket soc=null;//向客户发消息的socket
		DatagramPacket svrpac=null;//用于接收客户发过来的数据包
		DatagramPacket pac1=null;//用于发给客户的第一个数据包
//		DatagramPacket pac2=null;//用于发给客户的第二个数据包
		InetAddress clientIP=null;//客户的IP
		int clientPort;//客户发用于发消息的端口号
		String data=null;//从客户端接收来的数据
		String strToSend=null;//发给客户端的数据
//		DataInputStream sysin=null;/////用于服务器发消息给客户///////////
		String ToClient=null;
		byte[] buf=null;
		byte[] msg1=null;
//		byte[] msg2=null;
		try
		{
			buf=new byte[256];
			
//			msg2=new byte[256];
//			sysin=new DataInputStream(System.in);
			svrsoc=new DatagramSocket(9000);
			soc=new DatagramSocket();
			while(data!="quit")
			{
			//	msg1=new byte[256];
				svrpac=new DatagramPacket(buf,buf.length);
				svrsoc.receive(svrpac);
			/*  public String(byte[] ascii,int hibyte,int offset,int count)
			 *  的函数说明
                ascii - the bytes to be converted to characters.
  			    hibyte - the top 8 bits of each 16-bit Unicode character.
  			    从8位变为16位,设其前8位为0。
				offset - the initial offset.从那一位开始转变为String
				count - the length. 转变的长度
			 **/
				data=new String(buf,0,0,buf.length);
				clientIP=svrpac.getAddress();
				clientPort=svrpac.getPort();
				System.out.println("Client said:"+data);
				strToSend="I have received:"+data;
				//第一次发送
				msg1=new byte[strToSend.length()];
				
				/*public void getBytes(int srcBegin,
				 *					   int srcEnd,byte[] dst,int dstBegin)
				 *的参数说明
				 *  srcBegin - index of the first character in the string to copy.
					srcEnd - index after the last character in the string to copy.
					dst - the destination array.
					dstBegin - the start offset in the destination array. 
				 **/
				strToSend.getBytes(0,msg1.length,msg1,0);
				pac1=new DatagramPacket(msg1,msg1.length,clientIP,clientPort);
				soc.send(pac1);
			
			//第二次发送	
//				ToClient=sysin.readLine();
//				strToSend=strToSend+ToClient;
//				msg2=new byte[strToSend.length()];
				/*public void getBytes(int srcBegin,
				 *					   int srcEnd,byte[] dst,int dstBegin)
				 *的参数说明
				 *  srcBegin - index of the first character in the string to copy.
					srcEnd - index after the last character in the string to copy.
					dst - the destination array.
					dstBegin - the start offset in the destination array. 
				 */
//				strToSend.getBytes(0,msg2.length,msg2,0);
//				pac2=new DatagramPacket(msg2,msg2.length,clientIP,clientPort);
//				soc.send(pac2);	
								
			}
		}
		catch(Exception e)
		{
			System.out.println("Error:"+e);	
		}	
		finally
		{
			svrsoc.close();
			soc.close();
			System.exit(0);	
		}
	}	
}

⌨️ 快捷键说明

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