《java中使用多线程实现多服务功能.docx》由会员分享,可在线阅读,更多相关《java中使用多线程实现多服务功能.docx(9页珍藏版)》请在三一文库上搜索。
1、java 中使用多线程实现多服务功能import java.io.*;import .*;import java.util.*;class moreServerpublic static void main (String args) throws IOExceptionSystem.out.println (Server starting.n);/使用 8000 端口提供服务ServerSocketserver=newServerSocket(8000);while (true)/阻塞,直到有客户连接Socket sk = server.accept ();System.out.printl
2、n (Accepting Connection.n);/启动服务线程new ServerThread (sk).start ();/使用线程,为多个客户端服务 class ServerThread extends Threadprivate Socket sk;ServerThread (Socket sk)this.sk = sk;/线程运行实体public void run ()BufferedReader in = null;PrintWriter out = null;tryInputStreamReader isr;isr = new InputStreamReader (sk.ge
3、tInputStream ();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)
4、out.println (BYE);break;elseout.println (你好,我是服务器! );catch (IOException e)System.out.println (e.toString ();finallySystem.out.println(ClosingConnection.n);/最后释放资源tryif (in != null)in.close ();if (out != null)out.close ();if (sk != null)sk.close ();catch (IOException e)System.out.println(close err+e)
5、;/*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);InputStreamRead
6、er 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 (
7、BYE); System.out.println (in.readLine ();catch (IOException e)System.out.println (e.toString ();finallyout.println(END);/释放资源tryif (in != null)in.close ();if (out != null)out.close ();if (sk != null)sk.close ();catch (IOException e)/客户端public class SocketClientpublic static void main(String args) throws IOException,InterruptedExceptionInetAddressaddr=InetAddress.getByName(null);for(int i=0;i10;i+)new SocketThreadClient(addr);Thread.currentThread().sleep(1000);