您的位置:首页 > 编程语言 > Java开发

【Java】UDP聊天程序

2013-11-17 22:26 381 查看
package tmp;

import java.io.BufferedInputStream;
import java.net.*;
import java.util.Scanner;

public class TmpMain implements Runnable{
DatagramSocket sockSend,sockRecv;
DatagramPacket packSend,packRecv;
private byte bufSend[],bufRecv[];
private static InetAddress sendIP;
private static int portSend,portRecv;
private static final int MAX_LEN=1024;
Thread th;

TmpMain() throws Exception{
th=new Thread(this);
th.start();
sendData();
}

public void sendData() throws Exception{
@SuppressWarnings("resource")
Scanner cin=new Scanner(new BufferedInputStream(System.in));
String str="";
while(true){
str=cin.next();
bufSend=str.getBytes();
packSend=new DatagramPacket(bufSend,bufSend.length,sendIP,portSend);
sockSend=new DatagramSocket();
System.out.println("me: "+str);
sockSend.send(packSend);
}
}

public void run(){
while(true){
bufRecv=new byte[MAX_LEN];
packRecv=new DatagramPacket(bufRecv,MAX_LEN);
try{sockRecv=new DatagramSocket(portRecv);}catch(Exception e){}
try{sockRecv.receive(packRecv);}catch(Exception e){}
System.out.println("other: "+new String(packRecv.getData()).trim());
}
}

public static void main(String[] args) throws Exception{
@SuppressWarnings("resource")
Scanner cin=new Scanner(new BufferedInputStream(System.in));
System.out.println("input your ReceivePort: ");
portRecv=cin.nextInt();
System.out.println("input your SendPort: ");
portSend=cin.nextInt();
System.out.println("input your SendIP: ");
sendIP=InetAddress.getByName(cin.next());
System.out.println("Connected...");
new TmpMain();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: