java的serverthread,serverthread.java

package tiger.chat;import java.io.*;import java.net.*;public class ServerThread extends Thread{ // The Server that spawned us private Server server; // The Socket connected to our client private Socket socket; // Constructor. public ServerThread( Server server, Socket socket ) { // Save the parameters this.server = server; this.socket = socket; // Start up the thread start(); } // This runs in a separate thread when start() is called in the // constructor. public void run() { try { // Create a DataInputStream for communication; the client // is using a DataOutputStream to write to us DataInputStream din = new DataInputStream( socket.getInputStream() ); // Over and over, forever ... while (true) { // ... read the next message ... String message = din.readUTF(); // ... tell the world ... System.out.println( "Sending "+message ); // ... and have the server send it to all clients server.sendToAll( message ); } } catch( EOFException ie ) { // This doesn't need an error message } catch( IOException ie ) { // This does; tell the world! ie.printStackTrace(); } finally { // The connection is closed for one reason or another, // so have the server dealing with it server.removeConnection( socket ); } }}

// 文件名:moreServer.java import java.io.*; import java.net.*; import java.util.*; /** * <p>Title: 多线程服务器</p> * <p>Description: 本实例使用多线程实现多服务功能。</p> * <p>Copyright: Copyright (c) 2003</p> * <p>Filename: </p> * @author 杜江 * @version 1.0 */ 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); } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值