服务器的socket编程UDP协议,客户咨询<基于UDP协议的Socket编程(数据报式套接字)>...

1、DatagramPacket类的构造方法

bb5ec774ea914e42f460d0377f0387d3.png

2、DatagramSocket类的构造方法

fe0449721f4c180b45c10b5300adeb49.png

3、DatagramSocket类常用方法

10c87409ec92dc81f5381a0946aad41b.png

4、服务端

package com.ljb.app.datagram;

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.SocketAddress;

import java.net.SocketException;

/**

* 客户咨询服务端

* @author LJB

* @version 2015年3月12日

*/

public class AskServer {

/**

* @param args

*/

public static void main(String[] args) {

try {

// 创建接收方套接字(服务器),并绑定端口号

DatagramSocket ds = new DatagramSocket(8800);

// 确定数据包接收的数据的数组的大小

byte[] buf = new byte[1024];

// 创建接收类型的数据包,数据将存储在数组中

DatagramPacket dp = new DatagramPacket(buf,buf.length);

// 通过套接字接收数据

ds.receive(dp);

// 解析发送方发送的数据

String mess = new String(buf , 0 , dp.getLength());

System.out.println("客户端说:" + mess);

// 响应信息

String reply = "您好,我在,请咨询。";

byte[] buf2 = reply.getBytes();

// 响应地址

SocketAddress sa = dp.getSocketAddress();

// 数据包

DatagramPacket dp2 = new DatagramPacket(buf2 , buf2.length , sa);

// 发送

ds.send(dp2);

// 释放资源

ds.close();

} catch (SocketException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

5、客户端

package com.ljb.app.datagram;

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

import java.net.UnknownHostException;

/**

* 客户咨询客户端

* @author LJB

* @version 2015年3月12日

*/

public class AskClient {

/**

* @param args

*/

public static void main(String[] args) {

// 确定发送给服务器的信息,服务器地址,端口

String mess = "你好,我想咨询一个问题?";

byte[] buf = mess.getBytes();

InetAddress ia = null;

try {

ia = InetAddress.getByName("localhost");

} catch (UnknownHostException e) {

e.printStackTrace();

}

int port = 8800;

// 创建数据包,发送指定长度的信息到指定服务器的指定端口

DatagramPacket dp = new DatagramPacket(buf , buf.length , ia , port);

// 创建套接字对象

DatagramSocket ds = null;

try {

ds = new DatagramSocket();

} catch (SocketException e) {

e.printStackTrace();

}

// 发送数据包

try {

ds.send(dp);

} catch (IOException e) {

e.printStackTrace();

}

// 创建接收数组

byte[] buf2 = new byte[1024];

// 创建接收数据包

DatagramPacket dp2 = new DatagramPacket(buf2 , buf2.length);

// 接收数据

try {

ds.receive(dp2);

} catch (IOException e) {

e.printStackTrace();

}

// 解析接收到的数据

String reply = new String(buf2 , 0 , dp2.getLength());

System.out.println("服务器端说:" + reply);

// 释放资源

ds.close();

}

}

运行结果:

服务端:

客户端说:你好,我想咨询一个问题?

客户端:

服务器端说:您好,我在,请咨询。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值