Java UDP实例

Java UDP实例Server.javaimportjava.io.IOException;importjava.net.DatagramPacket;importjava.net.DatagramSocket;importjava.net.SocketException;publicclassServer{ /** *@paramargs */ publicstat

Server.java

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

public class Server {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			DatagramSocket  server = new DatagramSocket(6000);
			byte[] recvBuf = new byte[100];
	        DatagramPacket recvPacket = new DatagramPacket(recvBuf , recvBuf.length);
	        while(true){
	        	server.receive(recvPacket);
	        	String recvStr = new String(recvPacket.getData() , 0 , recvPacket.getLength());
	        	
	        	if(recvStr.equals("quit")){
	        		return;
	        	}
	        	System.out.println("received from "+ recvPacket.getAddress() +":" + recvStr);
	       
	        }
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Client.java

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


public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
		try {
			DatagramSocket client = new DatagramSocket();
			while(true){
				
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
				String str = null;
				while((str = br.readLine()) != null){
					
					byte[] sendBuf = str.getBytes();
					InetAddress addr = InetAddress.getByName("172.20.15.22");
					int port = 6000;
					DatagramPacket sendPacket = new DatagramPacket(sendBuf ,sendBuf.length , addr , port);
					client.send(sendPacket);
					if(str.equals("quit")){
						client.disconnect();
						return;
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

今天的文章Java UDP实例分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/25894.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注