注:下例仅为学习使用,高性能的服务器例子请采用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”