实验八 网络编程基础.docx
《实验八 网络编程基础.docx》由会员分享,可在线阅读,更多相关《实验八 网络编程基础.docx(18页珍藏版)》请在冰豆网上搜索。
实验八网络编程基础
实验八网络编程基础
1.实验目的
(1)掌握Socket通信。
(2)掌握UDP通信
2.实验内容
实验题1使用InetAddress类的方法获取
import.*;
publicclassmyIP{
publicstaticvoidmain(String[]args){
try{
InetAddressaddress1=InetAddress.getByName("");
System.out.println(address1.toString());
InetAddressaddress2=InetAddress.getByName(null);
System.out.println(address2.toString());
System.out.println(address2.getHostName());
}catch(UnknownHostExceptione){
System.out.println("无法找到");
}
}
}
实验题2使用URL类下载西北农林科技大学首页
importjava.awt.*;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
import.URL;
importjavax.swing.JButton;
importjavax.swing.JEditorPane;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JPanel;
importjavax.swing.JScrollPane;
importjavax.swing.JTextField;
publicclassWindwoURLextendsJFrameimplementsActionListener,Runnable{
JButtonbutton;
URLurl;
JTextFieldtext;
JEditorPaneeditPane;
byteb[]=newbyte[118];
Threadthread;
publicWindwoURL(){
text=newJTextField(20);
editPane=newJEditorPane();
editPane.setEditable(false);
button=newJButton("确定");
button.addActionListener(this);
thread=newThread(this);
JPanelp=newJPanel();
p.add(newJLabel("输入网址:
"));
p.add(text);
p.add(button);
JScrollPanescroll=newJScrollPane(editPane);
add(scroll,BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(160,60,420,300);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
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(Exceptione){
text.setText(""+e);
return;
}
}
}
publicclassmain{
publicstaticvoidmain(String[]args){
WindwoURLwin=newWindwoURL();
}
}
实验题3利用Socket类和ServerSocket类编写一个C/S程序,实现C/S通信。
客户端向服务器端发送Time命令,服务器端接受到该字符串后将服务器端当前时间返回给客户端;客户端向服务器端发送Exit命令,服务器端向客户端返回“Bye”后退出。
[基本要求]编写完整程序;两人一组,一个作为服务器端,另一人作为客户端。
服务器端和客户端都需要打印出接受到的消息和发出的命令。
packagenetwork;
import.*;
importjava.io.*;
importjava.util.*;
publicclassmyclient{
publicstaticvoidmain(String[]a){
Socketclient=null;
OutputStreamout=null;
InputStreamis=null;
try{
client=newSocket("127.0.0.1",8080);
while(true){
out=client.getOutputStream();
is=client.getInputStream();
DataInputStreamdis=newDataInputStream(is);
Scannerx=newScanner(System.in);
Stringb=x.nextLine();
out.write(b.getBytes());
System.out.println(dis.readUTF());
if(dis.readUTF()=="Bye!
"){client.close();break;}
else{
Scannerx1=newScanner(System.in);
Stringb1=x1.nextLine();
out.write(b1.getBytes());
}
dis.close();
}
}catch(Exceptionerr){
err.printStackTrace();
}
}
}
packagenetwork;
importjava.io.*;
importjava.util.*;
import.*;
publicclassTestServer{
publicstaticvoidmain(Stringa[])
{
ServerSockets=null;
try{
s=newServerSocket(8080);
while(true){
Sockets1=s.accept();
InputStreamin=s1.getInputStream();
byte[]bs=newbyte[60];
intlength=in.read(bs);
OutputStreamos=s1.getOutputStream();
DataOutputStreamdos=newDataOutputStream(os);
Stringstring=newString(bs,0,length);
if(string.equals("Time"))
{
System.out.println(string);
Dated=newDate();
Stringstr="现在时间是:
"+d.getHours()+":
"+d.getMinutes()+":
"+d.getSeconds();
dos.writeUTF(str);
}
elseif(string.equals("Exit")){
dos.writeUTF("Bye!
");
break;
}
else{
System.out.println(string);
Scannerx=newScanner(System.in);
Stringb=x.next();
dos.writeUTF(b);
}
s1.close();
}
}catch(IOExceptione){
System.out.println("程序正在运行出错:
"+e);
}
}
}
实验题4编写一数据报通信程序,实现简单的聊天功能。
图3.14聊天程序界面
[基本要求]两人一组编写完整程序。
“聊天内容”和“输入文本”分别为当前聊天的历史信息和当前要传送出去的聊天文本。
“确定”、“清空”、“退出”三个按钮分别实现发送当前聊天文本、清空当前聊天文本和退出系统的功能。
packagenetwork;
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
importjava.io.*;
import.*;
importjava.util.*;
publicclasstext4extendsJFrame{
publicJTextAreal;
publicJTextFieldj;
publicJButtonb1,b2,b3;
publictext4(){
this.setLayout(null);
this.setBounds(0,0,500,400);
this.setTitle("小松");
l=newJTextArea();
l.setBounds(20,20,300,250);
this.add(l);
j=newJTextField();
j.setBounds(20,285,300,65);
this.add(j);
b1=newJButton("确定");
b1.setFont(newFont("",Font.BOLD,23));
b1.setBounds(360,20,100,90);
b1.addActionListener(newButtonListener());
this.add(b1);
b2=newJButton("清空");
b2.setFont(newFont("",Font.BOLD,23));
b2.setBounds(360,140,100,90);
b2.addActionListener(newButtonListener());
this.add(b2);
b3=newJButton("退出");
b3.setFont(newFont("",Font.BOLD,23));
b3.setBounds(360,260,100,90);
b3.addActionListener(newButtonListener());
this.add(b3);
this.setVisible(true);
Threadthread=newThread(newserver());
thread.start();
}
publicstaticvoidmain(String[]a)
{
text4t=newtext4();
}
publicclassButtonListenerimplementsActionListener
{
publicvoidactionPerformed(ActionEvente)
{
if(e.getSource()==b1)
{
serverudpserver=newserver();
try{
udpserver.go();
}catch(IOExceptionex){
ex.printStackTrace();
System.exit
(1);
}
}
elseif(e.getSource()==b2)
{
l.setText("");
}
elseif(e.getSource()==b3)
{
System.exit(0);
}
}
}
publicclassserverimplementsRunnable{
InetAddressclientAddress;
publicvoidrun(){
DatagramPacketinDataPacket=null;
DatagramSocketdatagramSocket=null;
byte[]msg=newbyte[128];
try{
inDataPacket=newDatagramPacket(msg,msg.length);
datagramSocket=newDatagramSocket(8012);
}catch(Exceptione){
}
while(true){
if(datagramSocket==null)break;
else
try{
datagramSocket.receive(inDataPacket);
Stringstr1=newString(inDataPacket.getData(),0,inDataPacket.getLength());
l.append(str1+"\n");
}catch(Exceptione){}
}
datagramSocket.close();
}
publicvoidgo()throwsIOException{
Dated=newDate();
Stringtime="我是小松"+""+d.getHours()+":
"+d.getMinutes()+":
"+d.getSeconds()+"\n";
Stringstr=time+j.getText();
byte[]by=str.getBytes();
clientAddress=InetAddress.getLocalHost();
DatagramPacketoutDataPacket=newDatagramPacket(by,by.length,clientAddress,8912);
DatagramSocketdatagramSocket1=newDatagramSocket();
datagramSocket1.send(outDataPacket);
j.setText("");
datagramSocket1.close();
}
}
}
packagenetwork;
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
importjava.io.*;
import.*;
importjava.util.*;
publicclasstext3extendsJFrame{
publicJTextAreal;
publicJTextFieldj;
publicJButtonb1,b2,b3;
publictext3(){
this.setLayout(null);
this.setBounds(0,0,500,400);
this.setTitle("小鱼");
l=newJTextArea();
l.setBounds(20,20,300,250);
this.add(l);
j=newJTextField();
j.setBounds(20,285,300,65);
this.add(j);
b1=newJButton("确定");
b1.setFont(newFont("",Font.BOLD,23));
b1.setBounds(360,20,100,90);
b1.addActionListener(newButtonListener());
this.add(b1);
b2=newJButton("清空");
b2.setFont(newFont("",Font.BOLD,23));
b2.setBounds(360,140,100,90);
b2.addActionListener(newButtonListener());
this.add(b2);
b3=newJButton("退出");
b3.setFont(newFont("",Font.BOLD,23));
b3.setBounds(360,260,100,90);
b3.addActionListener(newButtonListener());
this.add(b3);
this.setVisible(true);
Threadthread1=newThread(newclient());
thread1.start();
}
publicstaticvoidmain(String[]a)
{
text3t=newtext3();
}
publicclassButtonListenerimplementsActionListener
{
publicvoidactionPerformed(ActionEvente)
{
if(e.getSource()==b1)
{
clientudpclient=newclient();
try{
udpclient.go();
}catch(IOExceptionex){
ex.printStackTrace();
System.exit
(1);
}
}
elseif(e.getSource()==b2)
{
l.setText("");
}
elseif(e.getSource()==b3)
{
System.exit(0);
}
}
}
publicclassclientimplementsRunnable{
InetAddressserverAddress;
publicvoidrun(){
DatagramPacketinDataPacket=null;
DatagramSocketdatagramSocket=null;
byteinMsg[]=newbyte[128];
try{
inDataPacket=newDatagramPacket(inMsg,inMsg.length);
datagramSocket=newDatagramSocket(8912);
}catch(Exceptione){}
while(true){
if(datagramSocket==null)break;
else
try{
datagramSocket.receive(inDataPacket);
Stringstr1=newString(inDataPacket.getData(),0,inDataPacket.getLength());
l.append(str1+"\n");
}catch(Exceptione){}
}
datagramSocket.close();
}
publicvoidgo()throwsIOException,UnknownHostException{
Dated=newDate();
Stringtime="我是小鱼"+""+d.getHours()+":
"+d.getMinutes()+":
"+d.getSeconds()+"\n";
Stringstr=time+j.getText();
byte[]msg=str.getBytes();
serverAddress=InetAddress.getLocalHost();
DatagramPacketoutDataPacket=newDatagramPacket(msg,msg.length,serverAddress,8012);
DatagramSocketdatagramSocket=newDatagramSocket();
datagramSocket.send(outDataPacket);
j.setText("");
datagramSocket.close();
}
}
}
实验题5客户机之间通过服务器交换数据。
提示:
为了适应传输各种类型的数据,必须