java中使用多线程实现多服务功能.doc_第1页
java中使用多线程实现多服务功能.doc_第2页
java中使用多线程实现多服务功能.doc_第3页
java中使用多线程实现多服务功能.doc_第4页
全文预览已结束

下载本文档

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

文档简介

import java.io.*;import .*;import java.util.*;class moreServer public static void main (String args) throws IOException System.out.println (Server starting.n); /使用8000端口提供服务 ServerSocket server = new ServerSocket (8000); while (true) /阻塞,直到有客户连接 Socket sk = server.accept (); System.out.println (Accepting Connection.n); /启动服务线程 new ServerThread (sk).start (); /使用线程,为多个客户端服务class ServerThread extends Thread private Socket sk; ServerThread (Socket sk) this.sk = sk; /线程运行实体 public void run () BufferedReader in = null; PrintWriter out = null; try InputStreamReader isr; isr = new InputStreamReader (sk.getInputStream (); in = new BufferedReader (isr); out = new PrintWriter ( new BufferedWriter( new OutputStreamWriter( sk.getOutputStream (), true); while(true) /接收来自客户端的请求,根据不同的命令返回不同的信息。 String cmd = in.readLine (); System.out.println(cmd); if (cmd = null) break; cmd = cmd.toUpperCase (); if (cmd.startsWith (BYE) out.println (BYE); break; else out.println (你好,我是服务器!); catch (IOException e) System.out.println (e.toString (); finally System.out.println (Closing Connection.n); /最后释放资源 try if (in != null) in.close (); if (out != null) out.close (); if (sk != null) sk.close (); catch (IOException e) System.out.println(close err+e); /*SocketClient.java*/import java.io.*;import .*; class SocketThreadClient extends Thread public static int count = 0;/构造器,实现服务 public SocketThreadClient (InetAddress addr) count+; BufferedReader in = null; PrintWriter out = null; Socket sk = null; try /使用8000端口 sk = new Socket (addr, 8000); InputStreamReader isr; isr = new InputStreamReader (sk.getInputStream (); in = new BufferedReader (isr); /建立输出 out = new PrintWriter ( new BufferedWriter( new OutputStreamWriter( sk.getOutputStream (), true); /向服务器发送请求 System.out.println(count:+count); out.println (Hello); System.out.println (in.readLine (); out.println (BYE); System.out.println (in.readLine (); catch (IOException e) System.out.println (e.toString (); finally out.println(END); /释放资源 try if (in != null) in.close (); if (out != null) out.close (); if (sk != null) sk.close (); catch (IOException e) /客户端public class SocketClient public static void main(String args) throws IOException,InterruptedException InetAddress addr

温馨提示

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

评论

0/150

提交评论