2 weixin 34433135 weixin_34433135 于 2016.03.27 23:59 提问

利用数据报通信的c/s程序

为什么我把客户端接口绑定为3456,但是服务器收到客户端接口为24,然后改了3456为别的数之后,收到依旧是24,而书上的是3456.图片图片图片图片

3个回答

caozhy
caozhy   Ds   Rxr 2016.03.28 00:09
已采纳

receivePacket.getLength()
这是包长度,不是端口号。

weixin_34433135
weixin_34433135 谢谢
一年多之前 回复
weixin_34433135
weixin_34433135   2016.03.28 00:06

import java.net.*;import java.io.*;import java.util.*;public class UDPServer { public static void main(String[] args){ try{ DatagramSocket receiveSocket = new DatagramSocket(5000); byte buf[] = new byte[1000]; DatagramPacket receivePacket = new DatagramPacket(buf,buf.length); System.out.println("starting to receive packet"); while(true){ receiveSocket.receive(receivePacket); String name = receivePacket.getAddress().toString(); System.out.println("\n来自主机:"+name+"\n端口:"+receivePacket.getLength()); String s = new String(receivePacket.getData(),0,receivePacket.getLength()); System.out.println("the received data: "+s); } } catch(SocketException e){ e.printStackTrace(); System.exit(1); } catch(IOException e){ System.out.println("网络通信出现错误,问题在"+e.toString()); } }

weixin_34433135
weixin_34433135   2016.03.28 00:07

import java.net.*;import java.io.*;import java.util.*;public class UDPClient { public static void main(String[] args){ try{ DatagramSocket sendSocket = new DatagramSocket(3456); String string = "hello!This is the client"; byte[] databyte = new byte[100]; databyte = string.getBytes(); DatagramPacket sendPacket = new DatagramPacket(databyte,string.length(),InetAddress.getByName("127.0.0.1"),5000); sendSocket.send(sendPacket); System.out.println("send the data:hello! this is the client"); } catch(SocketException e){ System.out.println("不能打开数据报Socket,或数据报Socket无法与指定端口连接!"); } catch(IOException ioe){ System.out.println("网络通信出现错误,问题在:"+ioe.toString()); } }}

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!