UPD组包问题,请教各位大侠

木棉花大榕树 2003-02-17 04:09:31
char a=1,包中定长为1
short b=1,包中定长为2
String c="abcd",包中定长为15

即是要组成一个定长为18的包,包里赋值a,b,c,
c++里可以用memset到buff去.
但是不知道Java怎么实现到byte[]中去.
...全文
36 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
木棉花大榕树 2003-02-18
  • 打赏
  • 举报
回复
你这是UDP发送的实现,我要的是组包的过程,怎么样组成我要的定长包,数据放在特定位置.(类似一个接口)
mzhenjun 2003-02-17
  • 打赏
  • 举报
回复
import java.io.*;
import java.net.*;

/**
* This class sends the specified text or file as a datagram to the
* specified port of the specified host.
**/
public class UDPSend
{
public static final String usage = "Usage: java UDPSend ...\n" + " or: java UDPSend -f ";

public static void main(String args[])
{
try
{
// Check the number of arguments
if (args.length < 3)
throw new IllegalArgumentException("Wrong number of args");

// Parse the arguments
String host = args[0];
int port = Integer.parseInt(args[1]);

// Figure out the message to send.
// If the third argument is -f, then send the contents of the file
// specified as the fourth argument. Otherwise, concatenate the
// third and all remaining arguments and send that.
byte[] message;
if (args[2].equals("-f"))
{
File f = new File(args[3]);
int len = (int)f.length(); // figure out how big the file is
message = new byte[len]; // create a buffer big enough
FileInputStream in = new FileInputStream(f);
int bytes_read = 0, n;
do
{ // loop until we've read it all
n = in.read(message, bytes_read, len-bytes_read);
bytes_read += n;
} while((bytes_read < len)&& (n != -1));
}
else
{ // Otherwise, just combine all the remaining arguments.
String msg = args[2];
for (int i = 3; i < args.length; i++) msg += " " + args[i];
message = msg.getBytes();
}

// Get the internet address of the specified host
InetAddress address = InetAddress.getByName(host);

// Initialize a datagram packet with data and address
DatagramPacket packet = new DatagramPacket(message, message.length,address, port);

// Create a datagram socket, send the packet through it, close it.
DatagramSocket dsocket = new DatagramSocket();
System.out.println("Server Started!");

dsocket.send(packet);

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String info=null;
boolean done=false;
while(!done)
{
info=in.readLine();
if(info.length()!=0)
{
if(info.equals("bye"))
done=true;

message=info.getBytes();
packet=new DatagramPacket(message,message.length,address,port);
dsocket.send(packet);
}
}
dsocket.close();
}
catch (Exception e)
{
System.err.println(e);
System.err.println(usage);
}
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧