当柳上原的风吹向天际的时候...

真正的快乐来源于创造

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  368 Posts :: 1 Stories :: 201 Comments :: 0 Trackbacks
注:下例仅为学习使用,高性能的服务器例子请采用NIO方案。

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ThreadedServer{
    
public static void main(String[] args) throws IOException{
        ServerSocket s
=new ServerSocket(9999);
        
        
while(true){
            Socket incoming
=s.accept();
            InetAddress address
=incoming.getInetAddress();
            System.out.println(
"开始与"+address+"进行通讯.");
            
            
new Thread(new EchoHandler(incoming)).start();
        }
    }
}

class EchoHandler implements Runnable{
    
private Socket incoming;
    
    
public EchoHandler(Socket incoming){
        
this.incoming=incoming;
    }
    
    
    
public void run(){
        
try{
            InputStream  inStram
=incoming.getInputStream();
            OutputStream outStream
=incoming.getOutputStream();
            
            Scanner in
=new Scanner(inStram);
            PrintWriter out
=new PrintWriter(outStream);
            out.println(
"你好!输入Bye退出。");
            
            
while(in.hasNextLine()){
                String line
=in.nextLine();
                System.out.println(
"客户端说:"+line);
                
                
if(line.equalsIgnoreCase("Bye")){
                    
break;
                }
                
else if(line.equalsIgnoreCase("login")){
                    System.out.println(
"客户端想登录");
                }
                
else if(line.equalsIgnoreCase("register")){
                    System.out.println(
"客户端想注册");                
                }
                
else if(line.equalsIgnoreCase("dispacth")){
                    System.out.println(
"客户端想转发信息");
                }
                
else if(line.equalsIgnoreCase("userlist")){
                    System.out.println(
"客户端想得到用户列表");
                }
                
else{
                    out.println(
"收到:"+line);
                }
            }
        }
        
catch(Exception ex){
            ex.printStackTrace();
        }
        
finally{
            
try {
                incoming.close();
            } 
catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

可采用Telnet与上述服务器端通信,Vista上Telnet可如下方式开启:
1、打开控制面板;
2、在左侧选择“经典视图”,然后在右侧选择“程序和功能”;
3、在出现的“程序和功能”窗口左侧中点击“打开或关闭Windows功能”;
4、在弹出的“Windows功能”窗口中勾选上“Telnet客户端”;
5、确定后退出,Windows会自动开始配置激活;
6、在“开始搜索”框中输入“telnet 127.0.0.1 9999



posted on 2010-12-23 14:19 何杨 阅读(457) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: