bootcool 原作
我最近也在研究用Java實現oicq。
這是我的客戶端的簡單編程實現。
主要是通過udp方式,實現用戶間的對話。
其中運用了序列化類的方法。
以下是源代碼,請多提意見。
//發送消息類
Message.Java
import Java.io.Serializable;
public class Message implements Serializable{
private String msg;
private String id;
private String destid;
public Message(String msg, String id, String destid) {
this.msg = msg;
this.id = id;
this.destid = destid;
}
//獲得消息內容
public String getMessage() {
return msg;
}
//獲得發送方的ip
public String getID() {
return id;
}
//獲得接受方的ip
public String getDestID() {
return destid;
}
}
//接受方
Receiver.Java
import Java.Net.*;
import Java.io.*;
public class Receiver extends Thread {
private Message msg;
private DatagramPacket packet;
private DatagramSocket socket;
private byte[] recvBuf = new byte[500];
public Receiver() {
try{
//創建udp包以接受數據。
packet = new DatagramPacke(recvBuf,recvBuf.length);
//創建接受方的udp端口以接收數據
socket = new DatagramSocket(7002);
}
catch(Exception e){}
}
public void run() {
try {
while(true){
//接受數據
socket.receive(packet);
ByteArrayInputStream byteStream = new
ByteArrayInputStream(recvBuf);
ObjectInputStream is = new ObjectInputStream(new
BufferedInputStream(byteStram));
Object o = is.readObject();
msg = (Message)o;
is.close();
System.out.println(msg.getMessage());
}
}
catch(Throwable t) {
t.printStackTrace();
}
}
}
//發送方
Sender.Java
import Java.Net.*;
import Java.io.*;
public class Sender extends Thread {
private Message msg;
private DatagramSocket socket;
private DatagramPacket packet;
public Sender(Message msg) {
try {
this.msg = msg;
//獲得目的方的ip地址
String destID = msg.getDestID();
//獲得將要發送的消息內容
String destID = msg.getDestIDString message = msg.getMessage();
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(500);
ObjectOutputStream os = new ObjectOutputStream(new
BufferedOutputStream(byteStream));
os.writeObject(msg);
os.flush();
byte[] sendBuf = byteStream.toByteArray();
//創建udp數據包以發送數據
packet = new DatagramPacket(sendBuf,sendBuf.length,
InetAddress.getByName(destID),7002);
//創建發送udp套接字,指定套接字口。
socket = new DatagramSocket(7000);
os.close();
}
catch(Throwable t) {
t.printStackTrace();
}
}
public void run() {
try {
//發送消息
socket.send(packet);
//發送完畢關閉套接字。
socket.close();
}
catch(Throwable t) {
t.printStackTrace();
}
}
}
//測試程序
Udp_Chat.Java
import Java.io.*;
import Java.Net.*;
public class UDP_Chat {
public UDP_Chat(String s){
}
public static void main(String args[])throws Exception{
Message a = new Message("阿飛的卡","211.92.155.200" ,"211.92.155.200");
new Sender(a).start();
new Receiver().start();
}
}