javaUDP做的简易聊天软件

qq_27558803 2016-08-25 10:56:08
为什么我在发送端发送,空格之后的字就不会再接收端显示,而且不能发空格,求救,怎么改?
send端:
package UDP;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class UDPSendDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds =new DatagramSocket();
while(true){
Scanner in=new Scanner(System.in);
String str=in.next();
byte[] buf=str.getBytes();
InetAddress ip=InetAddress.getByName("192.168.191.1");
DatagramPacket dp=new DatagramPacket(buf, buf.length, ip,8888);
ds.send(dp);
if("over".equals(str)){
break;
}
}
ds.close();
}
}
Rec端:
package UDP;
import java.io.IOException;
import java.net.*;
public class UDPReceiveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket(8888);
while(true){
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
int port=dp.getPort();
String str=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+":"+port+"--"+str);
}
}
}
...全文
136 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
HerveyHall 2016-08-25
  • 打赏
  • 举报
回复
String str=in.next();
这句改成
String str=in.nextLine();
就可以了,java.util.Scanner类的next()方法的官方解释是读取到一个完整标记(complete token),其中包括空格,而nextLine()方法读取整行字符串
Eiualee 2016-08-25
  • 打赏
  • 举报
回复
UDPSend端可以用replace()方法吧空格转成一个字符串,然后Receive端接收的时候用replace()方法转过来就行了
qq_27558803 2016-08-25
  • 打赏
  • 举报
回复
谢谢大家,用2L的方法试了下,解决了,很好。感谢大家

62,614

社区成员

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

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