基于UDP协议的socket编程示例

Posted 三碗才能饱

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于UDP协议的socket编程示例相关的知识,希望对你有一定的参考价值。

客户端

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 LoginClient {
	public static void main(String[] args) {
		String info = "你好,我想咨询一个问题";
		byte[] infos = info.getBytes();
		//IP地址获取方法
		InetAddress ia;
		DatagramSocket socket =null;
		try {
			ia = InetAddress.getByName("localhost");
			DatagramPacket dp = new DatagramPacket(infos, infos.length, ia, 5000);
			socket = new DatagramSocket();
			socket.send(dp);
			
			//接收服务端信息
			byte[] replys = new byte[1024];
			DatagramPacket dp1 = new DatagramPacket(replys,replys.length);
			socket.receive(dp1);
			String reply = new String(dp1.getData(),0,dp1.getData().length);
			System.out.println("服务器说:"+reply);
			
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			socket.close();
		}
		
		
		
	}
}

 服务器端

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


public class LoginService {
    public static void main(String[] args) {
        DatagramSocket socket = null;
        byte[] info = new byte[1024];
        DatagramPacket dp = new DatagramPacket(info, info.length);
        try {
            socket = new DatagramSocket(5000);
            socket.receive(dp);
            
            String infos = new String(dp.getData(), 0, dp.getData().length);
            System.out.println("客户端说:"+infos);
            
            //给客户端一个响应
            String reply = "你好,有什么问题请说";
            SocketAddress sa = dp.getSocketAddress();
            DatagramPacket dp1 = new DatagramPacket(reply.getBytes(), 0, reply.getBytes().length, sa);
            socket.send(dp1);
            
            
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            socket.close();
        }
        
    }
}

 

以上是关于基于UDP协议的socket编程示例的主要内容,如果未能解决你的问题,请参考以下文章

基于UDP协议的socket套接字编程 基于socketserver实现并发的socket编程

Linux socket编程示例(最简单的TCP和UDP两个例子)

基于UDP协议之——socket编程

网络 基于UDP协议的socket编程

Linux----网络编程socket

基于TCP协议的Socket编程 / 基于UDP协议的Socket编程