《黑马程序员》socket---udp聊天

来源:互联网 发布:java json依赖包 编辑:程序博客网 时间:2024/05/28 06:08

------- android培训、java培训、期待与您交流! ----------



在学习视频时我知道了可以在java中可以通过socket编程实现简单的聊天效果。


设计:

在程序建立俩个线程,以个线程发送信息,一个线程循环接受外来的信息。

需要注意的是:发送端可以以广播地址作为发送地址,这样在你本机的网段里面所有的机器都能收你数据。下面是具体的实现:


package com.test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;public class SocketUdpDemp {/** * @param args * @throws SocketException  */public static void main(String[] args) throws SocketException {// TODO Auto-generated method stubDatagramSocket dsRe = new DatagramSocket(3333);DatagramSocket dsSe = new DatagramSocket();new Thread(new RectDemo(dsRe)).start();new Thread(new SendDemo(dsSe)).start();}}class RectDemo implements Runnable {//接收端线程DatagramSocketds= null;public RectDemo(DatagramSocket ds) {this.ds = ds;}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {byte []buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);//新建一个数据包ds.receive(dp);//接受端口数据String ip = dp.getAddress().toString();String dat = new String(dp.getData(),0,dp.getLength());System.out.println(ip+":"+dat);//打印出数据} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}/* 发送数据包 */class SendDemo implements Runnable {//发送端线程DatagramSocketds= null;public SendDemo(DatagramSocket ds) {this.ds = ds;}@Overridepublic void run() {// TODO Auto-generated method stubBufferedReader bufr = null;try {bufr = new BufferedReader(new InputStreamReader(System.in));//从键盘上得到数据String line = null;while ((line = bufr.readLine()) != null) {if (line.compareTo("exit") == 0) {//如果是exit就退出System.out.println("断开连接成功");System.exit(0);}byte []buf = line.getBytes();//将数据封包DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("182.101.92.226"),3333);ds.send(dp);//发送数据包}} catch (Exception e) {// TODO: handle exception}}}

总结: udp协议是不需要建立连接的,所以可以通过发包,收包的方式来进行多台电脑上的聊天。



0 0
原创粉丝点击