网络程序设计代码.docx_第1页
网络程序设计代码.docx_第2页
网络程序设计代码.docx_第3页
网络程序设计代码.docx_第4页
网络程序设计代码.docx_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

通过 getLocalHost()方法获得本地信息import .*; import java.util.*; class Exp13_2 public static void main (String args) throws UnknownHostException InetAddress localAddress = InetAddress.getLocalHost(); System.out.println(localAddress); System.out.println(localAddress.getHostName(); /获得主机名称 该例程使用InetAddress类,用于获得指定的计算机名称和IP地址,在该程序示例中,需要将各注释程序段一一测试运行。import .*;import java.util.*;class InetAddressDemopublic static void main (String args) throws UnknownHostException/获得本地主机信息/*InetAddress localAddress = InetAddress.getLocalHost();System.out.println(localAddress);*/获得本地hosts文件中的纪录主机/*String host = ;InetAddress address = InetAddress.getByName(host);System.out.println(address);*/根据指定域名获得IP/*String host = ;InetAddress addresses = InetAddress.getAllByName(host);for(InetAddress address : addresses)System.out.println(address);*/获得指定主机信息String host = localhost;if (args.length = 1)host = args 0;InetAddress ia = InetAddress.getByName (host);System.out.println (Canonical Host Name = + ia.getCanonicalHostName ();System.out.println (Host Address = + ia.getHostAddress ();System.out.println (Host Name = + ia.getHostName ();System.out.println (Is Loopback Address = + ia.isLoopbackAddress ();/获得本地主机所有IP地址/* Enumeration netInterfaces = null; try netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements() NetworkInterface ni = netInterfaces.nextElement(); System.out.println(DisplayName: + ni.getDisplayName(); System.out.println(Name: + ni.getName(); Enumeration ips = ni.getInetAddresses(); while (ips.hasMoreElements() System.out.println(IP: + ips.nextElement().getHostAddress(); catch (Exception e) e.printStackTrace(); */ /根据IP地址构造InetAddress /*byte ip = new byte (byte) 202, (byte) 117, (byte)128 , 7;InetAddress address1 = InetAddress.getByAddress(ip);InetAddress address2 = InetAddress.getByAddress(, ip);System.out.println(address1);System.out.println(address2);*/ 1)UDP时钟校对,该程序实例中包括2段程序,分别运行在2个不同的进程上,如果在一台计算机上运行,注意为服务器端和客户端设置不同的UDP端口以免冲突。1)UDP时钟校对服务端点程序import java.io.*;import .*;import java.util.*;/ 引入工具库, 提供日期和时间类public class DatagramServerpublic static void main(String args ) throws IOException/ 新建立一个服务器线程对象new QuoteServerThread().start();class QuoteServerThread extends Thread/ 定义一个服务器线程/ 新建一个DatagramSocket对象, 通信连接private DatagramSocket socket = null;/ 新建数据输入对象, 向网络输入private DataInputStream in = null;/ 循环控制,保证时间服务器长期运行private boolean moreQuotes = true;public QuoteServerThread() throws IOException/ 时间服务器构造方法super(QuoteServerThread);/ 在1080端口建立监听socket = new DatagramSocket(1080);public void run()/ 线程运行主方法while(moreQuotes)/ 无限循环发送时间信息trybyte buf = new byte256; /开辟数据缓冲区 ,256 byte 用于接收和发送数据/ 建立一个DatagramPacket,指向buf缓冲区,容量256, 用于接收数据DatagramPacket packet = new DatagramPacket(buf, buf.length);socket.receive(packet);/ 接收数据System.out.println(当前的数据: + new String(packet.getData();/获取时间日期String dString = new String( + Calendar.HOUR + Calendar.MINUTE); / 将string数据转换为bytedString.getBytes(0, dString.length(), buf, 0); / 目标IP, 已收到数据报的发送IP InetAddress address = packet.getAddress();int port = packet.getPort();/ 目标PORT/ 形成待发送数据报packet = new DatagramPacket(buf, buf.length, address, port);socket.send(packet);/ 发送数据报catch(IOException e)e.printStackTrace();socket.close(); / 关闭连接2)UDP时钟校对客户端程序import java.io.*;import .*;import java.util.*;import java.awt.*;import java.awt.event.*public class DatagramClient extends FrameLabel showTime,l1;TextField serverName;Button b1;Boolean showSwitch;Panel p1;String hostName;Font myFont = new Font(Dialog, Font.BOLD, 24);public static void main(String args)DatagramClient dc = new DatagramClient();public DatagramClient()super(时钟客户段);setFont(myFont);setLayout(new BorderLayout();serverName = new TextField(localhost);b1 = new Button(连接);l1 = new Label(服务器名称);showTime = new Label();showSwitch = true;p1 = new Panel();p1.add(l1);p1.add(serverName);add(p1,BorderLayout.NORTH);add(showTime,BorderLayout.CENTER);add(b1,BorderLayout.SOUTH);b1.addActionListener(new Listener();serverName.addActionListener(new Listener();pack();show();class Listener implements ActionListenerpublic void actionPerformed(ActionEvent e)if(e.getSource() = serverName) /连接制定的服务器hostName = serverName.getText();else if(e.getSource() = b1) /改变接受服务器时间的BOOL开关hostName = serverName.getText();if(showSwitch = false)showSwitch = true;b1.setLabel(断开);elseshowSwitch = false;b1.setLabel(连接);showTime();public void showTime()DatagramSocket socket;InetAddress address;DatagramPacket packet;String received;byte buf = new byte256;trysocket = new DatagramSocket();address = InetAddress.getByName(hostName);/将字符串转换为字节数组buf = UDP client Data Transfer.getBytes();packet = new DatagramPacket(buf, buf.length, address, 1080);socket.send(packet);packet = new DatagramPacket(buf, buf.length);socket.receive(packet);received = new String(packet.getData(), 0);showTime.setText(received);socket.close();catch(Exception e) 文件读写1. import java.io.*;2. class fileInfo 3. public static void main(String args) throws IOException 4. File fileToCheck;5. if(args.length0)6. for(int i=0;iargs.length;i+)7. fileToCheck=new File(argsi);8. info(fileToCheck);9. 10. else11. System.out.println(命令行未给出文件!);12. 13. 14. public static void info(File f) throws IOException使用文件类File可以获取文件的各种信息15. File f=new File(“datatemp.dat”);16. f.getName():返回文件名 temp.dat17. f.getParent():返回文件所在目录名 data18. f.getPath():返回文件路径 datatemp.dat19. f.getAbsolutePath():返回绝对路径 datatemp.dat20. f.exists():文件是否存在21. f.canWrite(), f.canRead():文件是否可写、读22. f.isFile(), f.isDirectory():是否为文件或目录23. f.lastModified(), f.length(), f.delete():24. 文件的最后修改日期、长度;删除文件25. f.mkdir(), f.list():创建一个目录;列出目录下所有的文件在生成一个随机文件对象时,除了指明文件对象和文件名之外,还需要指明访问文件的模式。File f = new File(“file.txt”);new RandomAccessFile(f, “r”);new RandomAccessFile(f, “rw”);new RandomAccessFile(“file1.txt”, “r”);new RandomAccessFile(“file2.txt”, “rw”);1. import java.io.*;2. public class randomfile 3. 4. public static void main(String args)5. 6. int data_arr=12,31,56,23,27,1,43,65,4,99;7. try8. RandomAccessFile randf=new RandomAccessFile(“temp.dat“, “RW“);9. for (int i=0;i=0;i-)12. randf.seek(i*4);13. System.out.println(randf.readInt();14. 15. randf.close();16. catch (IOException e)17. System.out.println(“File access error: “+e); 多线程TCP多线程通信import java.io.*;import .*;import java.util.*;SuppressWarnings(value=deprecation,unchecked)public class MultiServer extends ThreadServerSocket serverSocket = null;boolean listening = true;int port = 1080;int count;public MultiServer()tryserverSocket = new ServerSocket(port);System.out.println(The Chat Server is listening on + port);catch(IOException e)System.err.println(Cant listen on Port);System.exit(1);count = 0;while(listening)try/new ClientServiceThread(clients, clientSocket).start();new ClientServiceThread(serverSocket.accept().start();count += 1;System.out.println(The Chat Server get + count + Clients);catch(IOException e)System.err.println(Cant Accept the Client Connection Apply);tryserverSocket.close();catch(IOException e)System.exit(1);this.start();public static void main(String args)MultiServer ms = new MultiServer();class ClientServiceThread extends Threadprivate String name = Client;private Socket socket = null;private Vector clients = null;public ClientServiceThread(Socket socket)super(ClientServiceThread);this.socket = socket;public ClientServiceThread(Vector clients, Socket socket)super(ClientServiceThread);this.socket = socket;this.clients = clients;public void run()tryDataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream();PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream(), 1024), true);String inputLine, outputLine;GreetingProtocol greeting = new GreetingProtocol();outputLine = cessInput(null);out.println(Welcome to My Chat Server,Please REG your Name, Format: name = yourname);out.flush();while(inputLine = in.readLine() != null)System.out.println( + Say: + inputLine);if(inputLine.startsWith(name) = inputLine.substring(inputLine.indexOf(=) + 1);out.println(Your Name + + is REG);out.flush();elseoutputLine = cessInput(inputLine);out.println(outputLine);out.flush();if(inputLine.equals(bye) break;out.close();in.close();socket.close();catch(IOException e)e.printStackTrace();举例,要进行一组数 1至 30 的累计,分为 3 个线程,每个线程都是从该集合中取 10 个数,分别累加,最后将这些线程的和再加在一起。如代码 4-5 所示。class Sum /共享资源,计数器 count private int count;/共享资源 synchronized public int add() count = count + 1; return count; class SumThread implements Runnable/定义线程 private Sum sd;private int sum = 0; private String name = null; public SumThread(String name, S = name; this.sd = sd; public void run()/必需的重写 try for(int i=0;i10;i+) sum += sd.add(); Thread.sleep(100) Thread.sleep(1000);catch(Exception e) System.out.println(name + 累加和: + sum); public int getSum() return sum; class SumDemo public static void main(String args) throws Exception Thread t = Thread.currentThread();/获得当前主线程 Sum sd = new Sum();/代表共享资源的变量 SumThread st1 = new SumThread(线程 1,sd); /创建子线程 SumThread st2 = n

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论