黑马程序员技术交流社区
标题:
Socket udp 中文乱码了。奇怪
[打印本页]
作者:
ZhaoYuBetter
时间:
2013-5-17 12:42
标题:
Socket udp 中文乱码了。奇怪
本帖最后由 ZhaoYuBetter 于 2013-5-26 08:49 编辑
程序如下,麻烦看一下:
public class UdpSend {
public static void main(String[] args) throws Exception {
// 1. 创建 udp服务,通过 DatagramSocket 对象, 会随机分配一个端口进行数据发送
DatagramSocket ds = new DatagramSocket();
// 2.确定数据,并封装成数据包
// 使用键盘输入来获取
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while(true) {
line = br.readLine();
if(line.equals("886")) {
break;
}
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("127.0.0.1"), 10000);
// 3.通过 socket 服务,将数据包发送出去,通过 send 方法
ds.send(dp);
}
// 4.关闭资源
ds.close();
}
}
复制代码
作者:
ZhaoYuBetter
时间:
2013-5-17 12:43
public class UdpRec {
public static void main(String[] args) throws Exception {
// 1.创建 udpsocket服务,建立端点
DatagramSocket ds = new DatagramSocket(10000);
while (true) {
// 2.定义数据包,用于存储数据
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
// 3.通过数据包的方法获取其中的数据;
ds.receive(dp); // 阻塞方法
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(), 0, dp.getLength());
int port = dp.getPort();
System.out.println(ip + "::" + data + "::" + port);
}
// 关闭资源
// ds.close();
}
}
复制代码
作者:
ZhaoYuBetter
时间:
2013-5-17 13:13
环境是 eclipse 。2个java 文件 是 utf-8 编码保存的。
作者:
Sword
时间:
2013-5-17 18:10
eclipse的文件一般都是GBK编码方式的,建议n你改一下编码方式:
右键选中文件--》点击最下面的Properties--》Text File Encoding下面修改成默认的GBK编码既可以了
希望对你有所帮助
作者:
ZhaoYuBetter
时间:
2013-5-18 09:37
Sword 发表于 2013-5-17 18:10
eclipse的文件一般都是GBK编码方式的,建议n你改一下编码方式:
右键选中文件--》点击最下面的Properties ...
嗯,谢谢,编码改好。是可以了
作者:
Sword
时间:
2013-5-21 09:47
如果问题已经解决了,那么大家请把帖子的类型改为“已解决”,谢谢合作
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2