java的UDP通信中,怎么从服务器端获取文本文件内容并显示在组件上

 我来答
缘Lai如茨
2016-04-29 · TA获得超过8631个赞
知道大有可为答主
回答量:7534
采纳率:92%
帮助的人:612万
展开全部
1:客户端程序
[java] view plain copy
package com.pb.udp;

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

/**
* 使用Sender类来代表客户端程序,
* @author ccna_zhang
*
*/
public class Sender {

public static void main(String[] args) {
String msg = "Hello, World";
byte[] buf = msg.getBytes();
try {
InetAddress address = InetAddress.getByName("192.168.1.80"); //服务器地址
int port = 8080; //服务器的端口号
//创建发送方的数据报信息
DatagramPacket dataGramPacket = new DatagramPacket(buf, buf.length, address, port);

DatagramSocket socket = new DatagramSocket(); //创建套接字
socket.send(dataGramPacket); //通过套接字发送数据

//接收服务器反馈数据
byte[] backbuf = new byte[1024];
DatagramPacket backPacket = new DatagramPacket(backbuf, backbuf.length);
socket.receive(backPacket); //接收返回数据
String backMsg = new String(backbuf, 0, backPacket.getLength());
System.out.println("服务器返回的数据为:" + backMsg);

socket.close();

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

2:服务器端程序
[java] view plain copy
package com.pb.udp;

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

/**
* 服务器端程序
* @author ccna_zhang
*
*/
public class Receiver {

public static void main(String[] args) {

try {
InetAddress address = InetAddress.getLocalHost();
int port = 8080;

//创建DatagramSocket对象
DatagramSocket socket = new DatagramSocket(port, address);

byte[] buf = new byte[1024]; //定义byte数组
DatagramPacket packet = new DatagramPacket(buf, buf.length); //创建DatagramPacket对象

socket.receive(packet); //通过套接字接收数据

String getMsg = new String(buf, 0, packet.getLength());
System.out.println("客户端发送的数据为:" + getMsg);

//从服务器返回给客户端数据
InetAddress clientAddress = packet.getAddress(); //获得客户端的IP地址
int clientPort = packet.getPort(); //获得客户端的端口号
SocketAddress sendAddress = packet.getSocketAddress();
String feedback = "Received";
byte[] backbuf = feedback.getBytes();
DatagramPacket sendPacket = new DatagramPacket(backbuf, backbuf.length, sendAddress); //封装返回给客户端的数据
socket.send(sendPacket); //通过套接字反馈服务器数据

socket.close(); //关闭套接字

} catch (UnknownHostException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}

3:程序运行结果
服务器端:
客户端发送的数据为:Hello, World
客户端:
服务器返回的数据为:Received
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式