一些学习java的练习作业 新手向参考资料 第6部分
源代码在线查看: chat.java
// 儅儖僠僉儍僗僩斉僠儍僢僩僾儘僌儔儉Chat.java
// 偙偺僾儘僌儔儉偼,儅儖僠僉儍僗僩傪巊偭偰僠儍僢僩婡擻傪採嫙偟傑偡
// 巊偄曽java Chat [億乕僩斣崋]
// 儔僀僽儔儕偺棙梡
import java.net.*;
import java.io.*;
// Chat僋儔僗
// Chat僋儔僗偼,庴怣僗儗僢僪傪嶌惉丒幚峴偟,憲怣傪扴摉偟傑偡
public class Chat {
final byte TTL = 1 ;//摨堦僙僌儊儞僩撪晹偺傒摓払壜擻偲偟傑偡
final String MULTICASTADDRESS = ("224.0.0.1") ;
// 儅儖僠僉儍僗僩傾僪儗僗224.0.0.1偼,
// 儖乕僞傪挻偊側偄応崌偺傾僪儗僗偱偡
int port = 6000 ;
// 僠儍僢僩梡偺億乕僩斣崋,巜掕偑側偗傟偽6000 斣偲偟傑偡
byte[] buff = new byte[1024] ;//憲怣梡僶僢僼傽
String myname ="" ;// 棙梡幰柤
int nameLength = 0 ;//棙梡幰柤偺挿偝
MulticastSocket soc = null ; // 儅儖僠僉儍僗僩僜働僢僩
InetAddress chatgroup = null ; //僠儍僢僩梡傾僪儗僗
// 僐儞僗僩儔僋僞棙梡幰柤側偳傪愝掕偟傑偡
public Chat(int portno){
port = portno ; //億乕僩斣崋偺愝掕
BufferedReader lineread
= new BufferedReader(new InputStreamReader(System.in)) ;
System.out.println("偍柤慜傪偳偆偧") ;
try{
myname = lineread.readLine() ;
}catch(Exception e){
e.printStackTrace() ;
System.exit(1) ;
}
System.out.println("傛偆偙偦" + myname + "偝傫.") ;
myname = myname + ">" ;
nameLength = (myname.getBytes()).length ;
for(int i = 0;i < nameLength;++i)
buff[i] = (myname.getBytes())[i] ;
}
// makeMulticastSocket儊僜僢僪
//MULTICASTADDRESS偵懳偟偰儅儖僠僉儍僗僩僜働僢僩傪嶌惉偟傑偡
public void makeMulticastSocket()
{
try{
chatgroup
= InetAddress.getByName(MULTICASTADDRESS) ;
soc = new MulticastSocket(port) ;
soc.joinGroup(chatgroup) ;
}
catch(Exception e){
e.printStackTrace() ;
System.exit(1);
}
}
// startLintener儊僜僢僪
// 僗儗僢僪梡僋儔僗ListenPacket偺僆僽僕僃僋僩傪惗惉偟,婲摦偟傑偡
public void startListener()
{
try{
ListenPacket lisner =
new ListenPacket(soc);
Thread lisner_thread = new Thread(lisner);
lisner_thread.start();//庴怣僗儗僢僪偺奐巒
}
catch(Exception e){
e.printStackTrace() ;
System.exit(1);
}
}
// sendMsgs儊僜僢僪
// 儅儖僠僉儍僗僩僷働僢僩偺憲怣傪扴摉偟傑偡
public void sendMsgs()
{
try{
// 憲怣儖乕僾
while(true){
int n = System.in.read(
buff,nameLength ,1024 - nameLength ) ;
if(n > 0){
DatagramPacket dp
= new DatagramPacket(
buff,n + nameLength,chatgroup,port) ;
soc.send(dp) ;
}
else break ;// 儖乕僾廔椆
}
}
catch(Exception e){
e.printStackTrace() ;
System.exit(1);
}
}
// quitGroup儊僜僢僪
// 愙懕傪廔椆偟傑偡
public void quitGroup()
{
try{
// 愙懕偺廔椆
System.out.println("愙懕廔椆") ;
soc.leaveGroup(chatgroup) ;
System.exit(0) ;
}
catch(Exception e){
e.printStackTrace() ;
System.exit(1);
}
}
// main儊僜僢僪
public static void main(String[] arg){
Chat c = null ;
int portno = 6000 ;
if(arg.length >= 1) portno = Integer.parseInt(arg[0]) ;
c = new Chat(portno) ;
c.makeMulticastSocket() ;
c.startListener() ;
c.sendMsgs() ;
c.quitGroup() ;
}
}
// ListenPacket僋儔僗
// 儅儖僠僉儍僗僩僷働僢僩傪庴怣偟傑偡
class ListenPacket implements Runnable {
MulticastSocket s = null;
// 僐儞僗僩儔僋僞儅儖僠僉儍僗僩僗儗僢僪傪庴偗庢傝傑偡
public ListenPacket(MulticastSocket soc){
s = soc;
}
// 張棟偺杮懱
public void run(){
byte[] buff = new byte[1024] ;
try{
while(true){
DatagramPacket recv
= new DatagramPacket(buff,buff.length) ;
s.receive(recv) ;
if(recv.getLength() > 0){
System.out.write(buff,0,recv.getLength()) ;
}
}
}catch(Exception e){
e.printStackTrace() ;
System.exit(1) ;
}
}
}