第十一章Java网络的基本知识
例子1
importjava.awt.;
importjava.awt.event.;
importjava.net.;
importjava.io.;
publicclassExample11_1
{publicstaticvoidmain(Stringargs[])
{newNetWin();
}
}
classNetWinextendsFrame
implementsActionListener,Runnable
{Buttonbutton;
URLurl;
TextFieldtext;
TextAreaarea;
byteb[]=newbyte[118];
Threadthread;
NetWin()
{text=newTextField(20);
area=newTextArea(12,12);
button=newButton("确定");
button.addActionListener(this);
thread=newThread(this);
Panelp=newPanel();
p.add(newLabel("输入网址:"));
p.add(text);
p.add(button);
add(area,BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(60,60,360,300);
setVisible(true);
validate();
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
publicvoidactionPerformed(ActionEvente)
{
if(!(thread.isAlive()))
thread=newThread(this);
try{
thread.start();
}
catch(Exceptionee)
{text.setText("我正在读取"+url);
}
}
publicvoidrun()
{try{intn=-1;
area.setText(null);
url=newURL(text.getText().trim());
InputStreamin=url.openStream();
while((n=in.read(b))!=-1)
{Strings=newString(b,0,n);
area.append(s);
}
}
catch(MalformedURLExceptione1)
{text.setText(""+e1);
return;
}
catch(IOExceptione1)
{text.setText(""+e1);
return;
}
}
}
例子2
importjava.awt.;
importjava.awt.event.;
importjava.net.;
importjava.io.;
importjavax.swing.JEditorPane;
publicclassExample11_2
{publicstaticvoidmain(Stringargs[])
{newWin();
}
}
classWinextendsFrame
implementsActionListener,Runnable
{Buttonbutton;
URLurl;
TextFieldtext;
JEditorPaneeditPane;
byteb[]=newbyte[118];
Threadthread;
publicWin()
{text=newTextField(20);
editPane=newJEditorPane();
editPane.setEditable(false);
button=newButton("确定");
button.addActionListener(this);
thread=newThread(this);
Panelp=newPanel();
p.add(newLabel("输入网址:"));
p.add(text);
p.add(button);
ScrollPanescroll=newScrollPane();
scroll.add(editPane);
add(scroll,BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(160,60,360,300);
setVisible(true);
validate();
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
publicvoidactionPerformed(ActionEvente)
{if(!(thread.isAlive()))
thread=newThread(this);
try{thread.start();
}
catch(Exceptionee)
{text.setText("我正在读取"+url);
}
}
publicvoidrun()
{try{intn=-1;
editPane.setText(null);
url=newURL(text.getText().trim());
editPane.setPage(url);
}
catch(Exceptione1)
{text.setText(""+e1);
return;
}
}
}
例子3
importjava.awt.;
importjava.awt.event.;
importjava.net.;
importjava.io.;
importjavax.swing.event.;
importjavax.swing.;
publicclassExample11_3
{publicstaticvoidmain(Stringargs[])
{newLinkWin();
}
}
classLinkWinextendsJFrameimplementsActionListener,Runnable
{Buttonbutton;
URLurl;
TextFieldtext;
JEditorPaneeditPane;
byteb[]=newbyte[118];
Threadthread;
publicLinkWin()
{text=newTextField(20);
editPane=newJEditorPane();
editPane.setEditable(false);
button=newButton("确定");
button.addActionListener(this);
thread=newThread(this);
Panelp=newPanel();
p.add(newLabel("输入网址:"));
p.add(text);
p.add(button);
ScrollPanescroll=newScrollPane();
scroll.add(editPane);
add(scroll,BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(60,60,360,300);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editPane.addHyperlinkListener(newHyperlinkListener()
{
publicvoidhyperlinkUpdate(HyperlinkEvente)
{if(e.getEventType()==
HyperlinkEvent.EventType.ACTIVATED)
{
try{editPane.setPage(e.getURL());
}
catch(IOExceptione1)
{editPane.setText(""+e1);
}
}
}});
}
publicvoidactionPerformed(ActionEvente)
{if(!(thread.isAlive()))
thread=newThread(this);
try{thread.start();
}
catch(Exceptionee)
{text.setText("我正在读取"+url);
}
}
publicvoidrun()
{try{
intn=-1;
editPane.setText(null);
url=newURL(text.getText().trim());
editPane.setPage(url);
}
catch(Exceptione1)
{text.setText(""+e1);
return;
}
}
}
例子4
importjava.net.;
publicclassDomainName
{publicstaticvoidmain(Stringargs[])
{try{InetAddressaddress_1=InetAddress.getByName("www.sina.com.cn");
System.out.println(address_1.toString());
InetAddressaddress_2=InetAddress.getByName("166.111.222.3");
System.out.println(address_2.toString());
}
catch(UnknownHostExceptione)
{System.out.println("无法找到www.sina.com.cn");
}
}
}
例子5
(1)客户端程序:
importjava.io.;
importjava.net.;
publicclassClient
{publicstaticvoidmain(Stringargs[])
{Strings=null;
Socketmysocket;
DataInputStreamin=null;
DataOutputStreamout=null;
try{
mysocket=newSocket("127.0.0.1",4331);
in=newDataInputStream(mysocket.getInputStream());
out=newDataOutputStream(mysocket.getOutputStream());
for(intk=1;k<100;k=k+2)
{out.writeUTF(""+k);
s=in.readUTF();//in读取服务器发来的信息,堵塞状态
System.out.println("客户收到:"+s);
Thread.sleep(500);
}
}
catch(Exceptione)
{System.out.println("服务器已断开"+e);
}
}
}
(2)服务器端程序:
importjava.io.;
importjava.net.;
publicclassServer
{publicstaticvoidmain(Stringargs[])
{ServerSocketserver=null;
Socketyou=null;
Strings=null;
DataOutputStreamout=null;
DataInputStreamin=null;
try{server=newServerSocket(4331);
}
catch(IOExceptione1)
{System.out.println(e1);
}
try{System.out.println("等待客户呼叫");
you=server.accept();//堵塞状态,除非有客户呼叫
out=newDataOutputStream(you.getOutputStream());
in=newDataInputStream(you.getInputStream());
while(true)
{s=in.readUTF();//in读取客户放入"线路"里的信息,堵塞状态
intm=Integer.parseInt(s);
out.writeUTF("你好:我是服务器");
out.writeUTF("你说的数是乘2后是:"+2m);
System.out.println("服务器收到:"+s);
Thread.sleep(500);
}
}
catch(Exceptione)
{System.out.println("客户已断开"+e);
}
}
}
例子6
(1)客户端
importjava.net.;
importjava.io.;
importjava.awt.;
importjava.awt.event.;
importjavax.swing.;
publicclassClient
{publicstaticvoidmain(Stringargs[])
{newComputerClient();
}
}
classComputerClientextendsFrameimplementsRunnable,ActionListener
{Buttonconnection,send;
TextFieldinputText,showResult;
Socketsocket=null;
DataInputStreamin=null;
DataOutputStreamout=null;
Threadthread;
ComputerClient()
{socket=newSocket();
setLayout(newFlowLayout());
Boxbox=Box.createVerticalBox();
connection=newButton("连接服务器");
send=newButton("发送");
send.setEnabled(false);
inputText=newTextField(12);
showResult=newTextField(12);
box.add(connection);
box.add(newLabel("输入三角形三边的长度,用逗号或空格分隔:"));
box.add(inputText);
box.add(send);
box.add(newLabel("收到的结果:"));
box.add(showResult);
connection.addActionListener(this);
send.addActionListener(this);
thread=newThread(this);
add(box);
setBounds(10,30,300,400);
setVisible(true);
validate();
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
publicvoidactionPerformed(ActionEvente)
{if(e.getSource()==connection)
{try//请求和服务器建立套接字连接:
{if(socket.isConnected())
{}
else
{InetAddressaddress=InetAddress.getByName("127.0.0.1");
InetSocketAddresssocketAddress=newInetSocketAddress(address,4331);
socket.connect(socketAddress);
in=newDataInputStream(socket.getInputStream());
out=newDataOutputStream(socket.getOutputStream());
send.setEnabled(true);
thread.start();
}
}
catch(IOExceptionee){}
}
if(e.getSource()==send)
{Strings=inputText.getText();
if(s!=null)
{try{out.writeUTF(s);
}
catch(IOExceptione1){}
}
}
}
publicvoidrun()
{Strings=null;
while(true)
{try{s=in.readUTF();
showResult.setText(s);
}
catch(IOExceptione)
{showResult.setText("与服务器已断开");
break;
}
}
}
}
(2)服务器端
importjava.io.;
importjava.net.;
importjava.util.;
publicclassServer
{publicstaticvoidmain(Stringargs[])
{ServerSocketserver=null;
Server_threadthread;
Socketyou=null;
while(true)
{try{server=newServerSocket(4331);
}
catch(IOExceptione1)
{System.out.println("正在监听");//ServerSocket对象不能重复创建
}
try{System.out.println("等待客户呼叫");
you=server.accept();
System.out.println("客户的地址:"+you.getInetAddress());
}
catch(IOExceptione)
{System.out.println("正在等待客户");
}
if(you!=null)
{newServer_thread(you).start();//为每个客户启动一个专门的线程
}
}
}
}
classServer_threadextendsThread
{Socketsocket;
DataOutputStreamout=null;
DataInputStreamin=null;
Strings=null;
booleanquesion=false;
Server_thread(Sockett)
{socket=t;
try{out=newDataOutputStream(socket.getOutputStream());
in=newDataInputStream(socket.getInputStream());
}
catch(IOExceptione)
{}
}
publicvoidrun()
{while(true)
{doublea[]=newdouble[3];
inti=0;
try{s=in.readUTF();//堵塞状态,除非读取到信息
quesion=false;
StringTokenizerfenxi=newStringTokenizer(s,",");
while(fenxi.hasMoreTokens())
{Stringtemp=fenxi.nextToken();
try{a[i]=Double.valueOf(temp).doubleValue();i++;
}
catch(NumberFormatExceptione)
{out.writeUTF("请输入数字字符");
quesion=true;
}
}
if(quesion==false)
{doublep=(a[0]+a[1]+a[2])/2.0;
out.writeUTF(""+Math.sqrt(p(p-a[0])(p-a[1])(p-a[2])));
}
}
catch(IOExceptione)
{System.out.println("客户离开");
return;
}
}
}
}
例子7
(1)服务器
Server.java
importjava.io.;
importjava.net.;
importjava.util.zip.;
publicclassServer
{publicstaticvoidmain(Stringargs[])
{ServerSocketserver=null;
ServerThreadthread;
Socketyou=null;
while(true)
{try{server=newServerSocket(4331);
}
catch(IOExceptione1)
{System.out.println("正在监听");
}
try{you=server.accept();
System.out.println("客户的地址:"+you.getInetAddress());
}
catch(IOExceptione)
{System.out.println("正在等待客户");
}
if(you!=null)
{newServerThread(you).start();
}
}
}
}
classServerThreadextendsThread
{Socketsocket;
ZipOutputStreamout;
Strings=null;
ServerThread(Sockett)
{socket=t;
try{out=newZipOutputStream(socket.getOutputStream());
}
catch(IOExceptione){}
}
publicvoidrun()
{try{out.putNextEntry(newZipEntry("Example.java"));
FileInputStreamreader=newFileInputStream("Example.java");
byteb[]=newbyte[1024];
intn=-1;
while((n=reader.read(b,0,1024))!=-1)
{out.write(b,0,n);//发送压缩后的数据到客户端。
}
out.putNextEntry(newZipEntry("E.java"));
reader=newFileInputStream("E.java");
n=-1;
while((n=reader.read(b,0,1024))!=-1)
{out.write(b,0,n);//发送压缩后的数据到客户端。
}
reader.close();
out.close();
}
catch(IOExceptione){}
}
}
(2)客户端
Client.java
importjava.net.;
importjava.io.;
importjava.awt.;
importjava.awt.event.;
importjava.util.zip.;
publicclassClientextendsFrameimplementsRunnable,ActionListener
{Buttonconnection,getFile;
TextAreashowResult;
Socketsocket=null;
ZipInputStreamin;
Threadthread;
publicClient()
{socket=newSocket();
connection=newButton("连接服务器,获取文件内容");
setLayout(newFlowLayout());
showResult=newTextArea(10,28);
add(connection);
add(showResult);
connection.addActionListener(this);
thread=newThread(this);
setBounds(100,100,460,410);
setVisible(true);
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
publicvoidrun()
{byteb[]=newbyte[1024];
ZipEntryzipEntry=null;
while(true)
{try{while((zipEntry=in.getNextEntry())!=null)
{showResult.append("\n"+zipEntry.toString()+":\n");
intn=-1;
while((n=in.read(b,0,1024))!=-1)
{Stringstr=newString(b,0,n);
showResult.append(str);
}
}
}
catch(IOExceptione){}
}
}
publicvoidactionPerformed(ActionEvente)
{if(e.getSource()==connection)
{try{if(socket.isConnected())
{}
else
{InetAddressaddress=InetAddress.getByName("127.0.0.1");
InetSocketAddresssocketAddress=newInetSocketAddress(address,4331);
socket.connect(socketAddress);
in=newZipInputStream(socket.getInputStream());
thread.start();
}
}
catch(IOExceptionee)
{System.out.println(ee);
}
}
}
publicstaticvoidmain(Stringargs[])
{Clientwin=newClient();
}
}
例子8
主机1
importjava.net.;importjava.awt.;importjava.awt.event.;
classShanghai_FrameextendsFrameimplementsRunnable,ActionListener
{TextFieldout_message=newTextField("发送数据到北京:");
TextAreain_message=newTextArea();
Buttonb=newButton("发送数据包到北京");
Shanghai_Frame()
{super("我是上海");
setSize(200,200);setVisible(true);
b.addActionListener(this);
add(out_message,"South");add(in_message,"Center");add(b,"North");
Threadthread=newThread(this);
thread.start();//线程负责接收数据包
}
publicvoidactionPerformed(ActionEventevent)//点击按扭发送数据包
{bytebuffer[]=out_message.getText().trim().getBytes();
try{InetAddressaddress=InetAddress.getByName("127.0.0.1");
DatagramPacketdata_pack=
newDatagramPacket(buffer,buffer.length,address,888);
DatagramSocketmail_data=newDatagramSocket();
in_message.append("数据报目标主机地址:"+data_pack.getAddress()+"\n");
in_message.append("数据报目标端口是:"+data_pack.getPort()+"\n");
in_message.append("数据报长度:"+data_pack.getLength()+"\n");
mail_data.send(data_pack);
}
catch(Exceptione){}
}
publicvoidrun()////接收数据包
{DatagramPacketpack=null;
DatagramSocketmail_data=null;
bytedata[]=newbyte[8192];
try{pack=newDatagramPacket(data,data.length);
mail_data=newDatagramSocket(666);
}
catch(Exceptione){}
while(true)
{if(mail_data==null)break;
else
try{mail_data.receive(pack);
intlength=pack.getLength();
InetAddressadress=pack.getAddress();
intport=pack.getPort();
Stringmessage=newString(pack.getData(),0,length);
in_message.append("收到数据长度:"+length+"\n");
in_message.append("收到数据来自:"+adress+"端口:"+port+"\n");
in_message.append("收到数据是:"+message+"\n");
}
catch(Exceptione){}
}
}
}
publicclassShanghai
{publicstaticvoidmain(Stringargs[])
{Shanghai_Frameshanghai_win=newShanghai_Frame();
shanghai_win.addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
shanghai_win.validate();
}
}
主机2
importjava.net.;importjava.awt.;importjava.awt.event.;
classBeijing_FrameextendsFrameimplementsRunnable,ActionListener
{TextFieldout_message=newTextField("发送数据到上海:");
TextAreain_message=newTextArea();
Buttonb=newButton("发送数据包到上海");
Beijing_Frame()
{super("我是北京");
setSize(200,200);setVisible(true);
b.addActionListener(this);
add(out_message,"South");add(in_message,"Center");add(b,"North");
Threadthread=newThread(this);
thread.start();//线程负责接收数据包
}
publicvoidactionPerformed(ActionEventevent)
{bytebuffer[]=out_message.getText().trim().getBytes();
try{InetAddressaddress=InetAddress.getByName("127.0.0.1");
DatagramPacketdata_pack=
newDatagramPacket(buffer,buffer.length,address,666);
DatagramSocketmail_data=newDatagramSocket();
in_message.append("数据报目标主机地址:"+data_pack.getAddress()+"\n");
in_message.append("数据报目标端口是:"+data_pack.getPort()+"\n");
in_message.append("数据报长度:"+data_pack.getLength()+"\n");
mail_data.send(data_pack);
}
catch(Exceptione){}
}
publicvoidrun()
{DatagramSocketmail_data=null;
bytedata[]=newbyte[8192];
DatagramPacketpack=null;
try{
pack=newDatagramPacket(data,data.length);
mail_data=newDatagramSocket(888);
}
catch(Exceptione){}
while(true)
{if(mail_data==null)break;
else
try{mail_data.receive(pack);
intlength=pack.getLength();
InetAddressadress=pack.getAddress();
intport=pack.getPort();
Stringmessage=newString(pack.getData(),0,length);
in_message.append("收到数据长度:"+length+"\n");
in_message.append("收到数据来自:"+adress+"端口:"+port+"\n");
in_message.append("收到数据是:"+message+"\n");
}
catch(Exceptione){}
}
}
}
publicclassBeijing
{publicstaticvoidmain(Stringargs[])
{Beijing_Framebeijing_win=newBeijing_Frame();
beijing_win.addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
beijing_win.validate();
}
}
例子9
(1)广播信息的主机
BroadCast.java
importjava.net.;
publicclassBroadCastextendsThread
{Strings="天气预报,最高温度32度,最低温度25度";
intport=5858;//组播的端口
InetAddressgroup=null;//组播组的地址
MulticastSocketsocket=null;//多点广播套接字
BroadCast()
{try
{
group=InetAddress.getByName("239.255.8.0");//设置广播组的地址为239.255.8.0
socket=newMulticastSocket(port);//多点广播套接字将在port端口广播
socket.setTimeToLive(1);//多点广播套接字发送数据报范围为本地网络
socket.joinGroup(group);//加入广播组,加入group后,socket发送的数据报
}//可以被加入到group中的成员接收到
catch(Exceptione)
{System.out.println("Error:"+e);
}
}
publicvoidrun()
{while(true)
{try{DatagramPacketpacket=null;//待广播的数据包
bytedata[]=s.getBytes();
packet=newDatagramPacket(data,data.length,group,port);
System.out.println(newString(data));
socket.send(packet);//广播数据包
sleep(2000);
}
catch(Exceptione)
{System.out.println("Error:"+e);
}
}
}
publicstaticvoidmain(Stringargs[])
{newBroadCast().start();
}
}
(2)接收广播的主机
Receive.java
importjava.net.;
importjava.awt.;
importjava.awt.event.;
publicclassReceiveextendsFrameimplementsRunnable,ActionListener
{intport;//组播的端口.
InetAddressgroup=null;//组播组的地址.
MulticastSocketsocket=null;//多点广播套接字.
Button开始接收,停止接收;
TextArea显示正在接收内容,显示已接收的内容;
Threadthread;//负责接收信息的线程.
boolean停止=false;
publicReceive()
{super("定时接收信息");
thread=newThread(this);
开始接收=newButton("开始接收");
停止接收=newButton("停止接收");
停止接收.addActionListener(this);
开始接收.addActionListener(this);
显示正在接收内容=newTextArea(10,10);
显示正在接收内容.setForeground(Color.blue);
显示已接收的内容=newTextArea(10,10);
Panelnorth=newPanel();
north.add(开始接收);
north.add(停止接收);
add(north,BorderLayout.NORTH);
Panelcenter=newPanel();
center.setLayout(newGridLayout(1,2));
center.add(显示正在接收内容);
center.add(显示已接收的内容);
add(center,BorderLayout.CENTER);
validate();
port=5858;//设置组播组的监听端口
try{
group=InetAddress.getByName("239.255.8.0");//设置广播组的地址为239.255.8.0
socket=newMulticastSocket(port);//多点广播套接字将在port端口广播
socket.joinGroup(group);//加入广播组,加入group后,socket发送的数据报
}//可以被加入到group中的成员接收到
catch(Exceptione){}
setBounds(100,50,360,380);
setVisible(true);
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
publicvoidactionPerformed(ActionEvente)
{if(e.getSource()==开始接收)
{开始接收.setBackground(Color.blue);
停止接收.setBackground(Color.gray);
if(!(thread.isAlive()))
{thread=newThread(this);
}
try{thread.start();
停止=false;
}
catch(Exceptionee){}
}
if(e.getSource()==停止接收)
{开始接收.setBackground(Color.gray);
停止接收.setBackground(Color.blue);
停止=true;
}
}
publicvoidrun()
{while(true)
{bytedata[]=newbyte[8192];
DatagramPacketpacket=null;
packet=newDatagramPacket(data,data.length,group,port);//待接收的数据包。
try{socket.receive(packet);
Stringmessage=newString(packet.getData(),0,packet.getLength());
显示正在接收内容.setText("正在接收的内容:\n"+message);
显示已接收的内容.append(message+"\n");
}
catch(Exceptione){}
if(停止==true)
{break;
}
}
}
publicstaticvoidmain(Stringargs[])
{newReceive();
}
}
|
|