网络编程(UDP协议-聊天程序)

时间:2023-10-06 22:01:02

网络编程中的UDP协议中聊天程序,发送端口,和接受端口。

发送端口(Send):

<span style="font-size:18px;">package cn.itcast.net.p3.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; public class Send implements Runnable{
private DatagramSocket ds; public Send(DatagramSocket ds){
this.ds=ds;
}
@Override
public void run(){
try{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line=bufr.readLine())!=null){
byte[] buf = line.getBytes();
DatagramPacket dp =
new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.3.5"),1001);
ds.send(dp);
if("886".equals(line))
break;
}
}catch(Exception e){
} }
}</span>

接受端口(Rece):

<span style="font-size:18px;">package cn.itcast.net.p3.chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket; public class Rece implements Runnable {
private DatagramSocket ds;
public Rece(DatagramSocket ds){
this.ds = ds;
}
@Override
public void run() {
try {
while(true){
//2、创建数据包
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
//3、使用接收方法将数据存储到数据包中
ds.receive(dp); //阻塞式的
//4、通过数据包对象方法,解析其中的数据
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String text = new String(dp.getData(),0,dp.getLength()); System.out.println(ip+":"+text);
if(text.equals("886")){
System.out.println(ip+".....退出聊天室");
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
} </span>