JAVA 语言实现简单的聊天室,附源代码

来源:互联网 发布:张海山锐线体简mac 编辑:程序博客网 时间:2024/05/16 15:19
package blog.seif.net.udp.mytest;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class ChatTest {
public static void main(String[] args) throws IOException {
DatagramSocket send = new DatagramSocket();
DatagramSocket rece = new DatagramSocket(13146);
new Thread(new Send(send)).start();
new Thread(new Rece(rece)).start();
}
}
//实现发送线程
class Send implements Runnable {
private DatagramSocket ds;
public Send(DatagramSocket ds) {
super();
this.ds = ds;
}


@Override
public void run() {
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
byte[] by = new byte[1024];
String line = null;
try {
while ((line = bufr.readLine()) != null) {
by = line.getBytes();


if ("over".equals(line)) {
break;
}
DatagramPacket dp;
try {
//IP地址为局域网地址,端口号务必需要未被占用的端口
dp = new DatagramPacket(by, by.length, InetAddress.getByName("192.168.1.100"), 13146);
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
}


}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//接收线程
class Rece implements Runnable {
private DatagramSocket ds;


public Rece(DatagramSocket ds) {
super();
this.ds = ds;
}
@Override
public void run() {
// TODO 自动生成的方法存根
while (true) {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
try {
ds.receive(dp);
String name = dp.getAddress().getHostName();
String ip = dp.getAddress().getHostAddress();
String str = new String(dp.getData(),0,dp.getLength());
if ("over".equals(dp.getData())) {
System.out.println("ok,88");
break;
}
System.out.println(name + "..." + ip + "..." + str);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
原创粉丝点击