黑马程序员技术交流社区
标题:
今天学了向老师网络编程这一章,自己设计了UDP聊天软件
[打印本页]
作者:
嘿嘿小学徒
时间:
2012-12-31 08:13
标题:
今天学了向老师网络编程这一章,自己设计了UDP聊天软件
package heima.net;
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 UDPChatDemo {
/**
* @param 黑马程序员
* -UDP聊天
* @author 高一航
*/
public static void main(String[] args) {
try {
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket recieveSocket = new DatagramSocket(10001);//监听本机的10001端口
new Thread(new Sender(sendSocket)).start();
new Thread(new Receiver(recieveSocket)).start();
} catch (SocketException e) {
e.printStackTrace();
}
}
}
class Sender implements Runnable {
private DatagramSocket ds;// 1,建立Socket端点
private DatagramPacket dp;// 2,定义数据包,用于存储数据;
public Sender(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
byte[] buf = new byte[1024];
String line;
try {
while ((line = in.readLine()) != null) {
buf = line.getBytes();
dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("127.0.0.1"), 10000);
ds.send(dp);// 3,通过socket发送方法,将数据发送
if ("bye".equalsIgnoreCase(line)) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
ds.close();
System.out.println("sender resources closed");
}
}
}
class Receiver implements Runnable {
private DatagramSocket ds;// 1,建立Socket端点
public DatagramPacket dp;// 2,定义数据包,用于存储数据;
public Receiver(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
byte[] buf = new byte[1024];
String ip;
String context;
try {
while (true) {
dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);//3,通过socket的receive方法将数据存入数据包
ip = dp.getAddress().getHostAddress();//获取IP
context = new String(dp.getData(), 0, dp.getLength());//获取内容
System.out.println(ip + " : " + context);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
ds.close();
System.out.println("Receiver resources closed");
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2