一、问答题
1.一个URL对象通常包含最基本的三部分信息:协议、地址、资源。
2.URL对象调用InputStreamopenStream() 方法可以返回一个输入流,该输入流指向URL对象所包含的资源。通过该输入流可以将服务器上的资源信息读入到客户端。
3.客户端的套接字和服务器端的套接字通过输入、输出流互相连接后进行通信。
4.使用方法accept(),accept()会返回一个和客户端Socket对象相连接的Socket对象。accept方法会堵塞线程的继续执行,直到接收到客户的呼叫。。
5.域名/IP。
四、编程题
1. (1)客户端
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client
{ public static void main(String args[])
{ newComputerClient();
}
}
class ComputerClient extendsFrame implements Runnable,ActionListener
{ Button connection,send;
TextField inputText,showResult;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread;
ComputerClient()
{ socket=new Socket();
setLayout(new FlowLayout());
Box box=Box.createVerticalBox();
connection=new Button("连接服务器");
send=new Button("发送");
send.setEnabled(false);
inputText=new TextField(12);
showResult=new TextField(12);
box.add(connection);
box.add(new Label("输入三角形三边的长度,用逗号或空格分隔:"));
box.add(inputText);
box.add(send);
box.add(new Label("收到的结果:"));
box.add(showResult);
connection.addActionListener(this);
send.addActionListener(this);
thread=new Thread(this);
add(box);
setBounds(10,30,300,400);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==connection)
{ try //请求和服务器建立套接字连接:
{ if(socket.isConnected())
{}
else
{ InetAddress address=InetAddress.getByName("127.0.0.1");
InetSocketAddresssocketAddress=new InetSocketAddress(address,4331);
socket.connect(socketAddress);
in =newDataInputStream(socket.getInputStream());
out = newDataOutputStream(socket.getOutputStream());
send.setEnabled(true);
thread.start();
}
}
catch (IOException ee){}
}
if(e.getSource()==send)
{ String s=inputText.getText();
if(s!=null)
{ try { out.writeUTF(s);
}
catch(IOException e1){}
}
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();
showResult.setText(s);
}
catch(IOException e)
{ showResult.setText("与服务器已断开");
break;
}
}
}
}
(2)服务器端
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Server_thread thread;
Socket you=null;
while(true)
{ try{ server=newServerSocket(4331);
}
catch(IOException e1)
{ System.out.println("正在监听"); //ServerSocket对象不能重复创建
}
try{ System.out.println(" 等待客户呼叫");
you=server.accept();
System.out.println("客户的地址:"+you.getInetAddress());
}
catch (IOException e)
{ System.out.println("正在等待客户");
}
if(you!=null)
{ new Server_thread(you).start(); //为每个客户启动一个专门的线程
}
}
}
}
class Server_thread extendsThread
{ Socket socket;
DataOutputStream out=null;
DataInputStream in=null;
String s=null;
boolean quesion=false;
Server_thread(Socket t)
{ socket=t;
try { out=new DataOutputStream(socket.getOutputStream());
in=newDataInputStream(socket.getInputStream());
}
catch (IOException e)
{}
}
public void run()
{ while(true)
{ double a[]=new double[3] ;
int i=0;
try{ s=in.readUTF();//堵塞状态,除非读取到信息
quesion=false;
StringTokenizer fenxi=newStringTokenizer(s," ,");
while(fenxi.hasMoreTokens())
{ String temp=fenxi.nextToken();
try{ a[i]=Double.valueOf(temp).doubleValue();i++;
}
catch(NumberFormatException e)
{ out.writeUTF("请输入数字字符");
quesion=true;
}
}
if(quesion==false)
{ double p=(a[0]+a[1]+a[2])/2.0;
out.writeUTF(""+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
}
}
catch (IOException e)
{ System.out.println("客户离开");
return;
}
}
}
}
2. 客户端Client.java
import java.net.*;
import java.io.*;
import java.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
public classClient
{ public static void main(String args[])
{ newChatClient();
}
}
class ChatClientextends Frame implements Runnable,ActionListener
{ Button connection,send;
TextField inputName,inputContent;
TextArea chatResult;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread;
String name="";
public ChatClient ()
{ socket=new Socket();
Box box1=Box.createHorizontalBox();
connection=new Button("连接服务器");
send=new Button("发送");
send.setEnabled(false);
inputName=new TextField(6);
inputContent=new TextField(22);
chatResult=new TextArea();
box1.add(new Label("输入妮称:"));
box1.add(inputName);
box1.add(connection);
Box box2=Box.createHorizontalBox();
box2.add(new Label("输入聊天内容:"));
box2.add(inputContent);
box2.add(send);
connection.addActionListener(this);
send.addActionListener(this);
thread=new Thread(this);
add(box1,BorderLayout.NORTH);
add(box2,BorderLayout.SOUTH);
add(chatResult,BorderLayout.CENTER);
setBounds(10,30,400,280);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==connection)
{ try
{ if(socket.isConnected())
{}
else
{ InetAddress address=InetAddress.getByName("127.0.0.1");
InetSocketAddresssocketAddress=new InetSocketAddress(address,666);
socket.connect(socketAddress);
in =newDataInputStream(socket.getInputStream());
out = newDataOutputStream(socket.getOutputStream());
name=inputName.getText();
out.writeUTF("姓名:"+name);
send.setEnabled(true);
if(!(thread.isAlive()))
thread=new Thread(this);
thread.start();
}
}
catch (IOException ee){}
}
if(e.getSource()==send)
{ String s=inputContent.getText();
if(s!=null)
{ try { out.writeUTF("聊天内容:"+name+":"+s);
}
catch(IOException e1){}
}
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();
chatResult.append("\n"+s);
}
catch(IOException e)
{ chatResult.setText("与服务器已断开");
try { socket.close();
}
catch(Exception exp) {}
break;
}
}
}
}
服务器端ChatServer.java
import java.io.*;
import java.net.*;
importjava.util.*;
public classChatServer
{ public static void main(String args[])
{ ServerSocket server=null;
Socket you=null;
Hashtable peopleList;
peopleList=new Hashtable();
while(true)
{ try { server=new ServerSocket(666);
}
catch(IOException e1)
{ System.out.println("正在监听");
}
try { you=server.accept();
InetAddressaddress=you.getInetAddress();
System.out.println("客户的IP:"+address);
}
catch (IOException e) {}
if(you!=null)
{ Server_thread peopleThread=newServer_thread(you,peopleList);
peopleThread.start();
}
else { continue;
}
}
}
}
classServer_thread extends Thread
{ String name=null;
Socket socket=null;
File file=null;
DataOutputStream out=null;
DataInputStream in=null;
Hashtable peopleList=null;
Server_thread(Socket t,Hashtable list)
{ peopleList=list;
socket=t;
try { in=new DataInputStream(socket.getInputStream());
out=newDataOutputStream(socket.getOutputStream());
}
catch (IOException e) {}
}
public void run()
{ while(true)
{ String s=null;
try{
s=in.readUTF();
if(s.startsWith("姓名:"))
{ name=s;
boolean boo=peopleList.containsKey(name);
if(boo==false)
{peopleList.put(name,this);
}
else
{ out.writeUTF("请换妮称:");
socket.close();
break;
}
}
else if(s.startsWith("聊天内容"))
{ String message=s.substring(s.indexOf(":")+1);
EnumerationchatPersonList=peopleList.elements();
while(chatPersonList.hasMoreElements())
{ ((Server_thread)chatPersonList.nextElement()).out.writeUTF("聊天内容:"+
message);
}
}
}
catch(IOException ee)
{ Enumeration chatPersonList=peopleList.elements();
while(chatPersonList.hasMoreElements())
{ try
{ Server_thread th=(Server_thread)chatPersonList.nextElement();
if(th!=this&&th.isAlive())
{ th.out.writeUTF("客户离线:"+name);
}
}
catch(IOException eee){}
}
peopleList.remove(name);
try { socket.close();
}
catch(IOException eee){}
System.out.println(name+"客户离开了");
break;
}
}
}
}
3.BroadCastWord.java
import java.io.*;
import java.net.*;
import java.awt.*;
importjava.awt.event.*;
importjavax.swing.Timer;
public classBroadCastWord extends Frame implements ActionListener
{ int port;
InetAddress group=null;
MulticastSocket socket=null;
Timer time=null;
FileDialog open=null;
Button select,开始广播,停止广播;
File file=null;
String FileDir=null,fileName=null;
FileReader in=null;
BufferedReader bufferIn=null;
int token=0;
TextArea 显示正在播放内容,显示已播放的内容;
public BroadCastWord()
{ super("单词广播系统");
select=new Button("选择要广播的文件");
开始广播=new Button("开始广播");
停止广播=new Button("停止广播");
select.addActionListener(this);
开始广播.addActionListener(this);
停止广播.addActionListener(this);
time=new Timer(2000,this);
open=new FileDialog(this,"选择要广播的文件",FileDialog.LOAD);
显示正在播放内容=new TextArea(10,10);
显示正在播放内容.setForeground(Color.blue);
显示已播放的内容=new TextArea(10,10);
Panel north=new Panel();
north.add(select);
north.add(开始广播);
north.add(停止广播);
add(north,BorderLayout.NORTH);
Panel center=new Panel();
center.setLayout(new GridLayout(1,2));
center.add(显示正在播放内容);
center.add(显示已播放的内容);
add(center,BorderLayout.CENTER);
validate();
try
{ port=5000;
group=InetAddress.getByName("239.255.0.0");
socket=new MulticastSocket(port);
socket.setTimeToLive(1);
socket.joinGroup(group);
}
catch(Exception e)
{ System.out.println("Error:"+ e);
}
setBounds(100,50,360,380);
setVisible(true);
addWindowListener(new WindowAdapter()
{ public voidwindowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==select)
{显示已播放的内容.setText(null);
open.setVisible(true);
fileName=open.getFile();
FileDir=open.getDirectory();
if(fileName!=null)
{ time.stop();
file=new File(FileDir,fileName);
try
{ file=new File(FileDir,fileName);
in=new FileReader(file);
bufferIn=new BufferedReader(in);
}
catch(IOException ee) { }
}
}
else if(e.getSource()==开始广播)
{ time.start();
}
else if(e.getSource()==time)
{ String s=null;
try { if(token==-1)
{ file=newFile(FileDir,fileName);
in=newFileReader(file);
bufferIn=newBufferedReader(in);
}
s=bufferIn.readLine();
if(s!=null)
{ token=0;
显示正在播放内容.setText("正在广播的内容:\n"+s);
显示已播放的内容.append(s+"\n");
DatagramPacketpacket=null;
byte data[]=s.getBytes();
packet=newDatagramPacket(data,data.length,group,port);
socket.send(packet);
}
else
{ token=-1;
}
}
catch(IOException ee) { }
}
else if(e.getSource()==停止广播)
{ time.stop();
}
}
public static voidmain(String[] args)
{ BroadCastWord broad=new BroadCastWord();
}
}
Receive.java
import java.net.*;
import java.awt.*;
importjava.awt.event.*;
public classReceive extends Frame implements Runnable,ActionListener
{ int port;
InetAddress group=null;
MulticastSocket socket=null;
Button 开始接收,停止接收;
TextArea 显示正在接收内容,显示已接收的内容;
Thread thread;
boolean 停止=false;
public Receive()
{ super("定时接收信息");
thread=new Thread(this);
开始接收=new Button("开始接收");
停止接收=new Button("停止接收");
停止接收.addActionListener(this);
开始接收.addActionListener(this);
显示正在接收内容=new TextArea(10,10);
显示正在接收内容.setForeground(Color.blue);
显示已接收的内容=new TextArea(10,10);
Panel north=new Panel();
north.add(开始接收);
north.add(停止接收);
add(north,BorderLayout.NORTH);
Panel center=new Panel();
center.setLayout(new GridLayout(1,2));
center.add(显示正在接收内容);
center.add(显示已接收的内容);
add(center,BorderLayout.CENTER);
validate();
port=5000;
try{group=InetAddress.getByName("239.255.0.0");
socket=new MulticastSocket(port);
socket.joinGroup(group);
}
catch(Exception e) { }
setBounds(100,50,360,380);
setVisible(true);
addWindowListener(new WindowAdapter()
{ public voidwindowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==开始接收)
{ 开始接收.setBackground(Color.blue);
停止接收.setBackground(Color.gray);
if(!(thread.isAlive()))
{ thread=new Thread(this);
}
try { thread.start();
停止=false;
}
catch(Exception ee) { }
}
if(e.getSource()==停止接收)
{ 开始接收.setBackground(Color.gray);
停止接收.setBackground(Color.blue);
thread.interrupt();
停止=true;
}
}
public void run()
{ while(true)
{ byte data[]=new byte[8192];
DatagramPacket packet=null;
packet=newDatagramPacket(data,data.length,group,port);
try { socket.receive(packet);
String message=newString(packet.getData(),0,packet.getLength());
显示正在接收内容.setText("正在接收的内容:\n"+message);
显示已接收的内容.append(message+"\n");
}
catch(Exception e) { }
if(停止==true)
{ break;
}
}
}
public static void main(String args[])
{ new Receive();
}
}