日期:2014-05-20  浏览次数:20799 次

求教java聊天工具服务器怎么转发数据
一个server 2个客户端 A 发送的数据到server 后 zerver怎么给B最好给段代码写过run函数 一个菜鸟的问题 随便什么流 TCP协议的套接字那种

------解决方案--------------------
一般server段用多线程来实现。
这是我写的客户端,通过telnet连接服务器的,希望对你有帮助
Java code

import java.io.*;
import java.net.*; 

public class Client {
     Socket socket;
     BufferedReader in;
     PrintWriter out;
     boolean  isQuit;
    public Client() {
        try {
            System.out.println("Try to Connect to 127.0.0.1:23");
            socket = new Socket("10.144.205.98",23);
        }catch(Exception e){
            System.out.println("wrong");
        }
        isQuit = false;
    }
    public  void  send(){
        SendThread sd = new SendThread(this);
        new Thread(sd).start();
    }
    public void server(){
        ServerThread st = new ServerThread(this);
        new Thread(st).start();
    }
   
    public void over(){
        try{
            out.close();
            in.close();
            socket.close();
        }catch(Exception e) {
            System.out.println("Wrong");
        }
        
    }
    public Socket getSocket(){return socket;}
    public boolean isQuit() {return isQuit;}
    public void quit(boolean b){isQuit = b;}
    
    
 public static void main(String[] args) throws Exception{
    Client c1 = new Client();
    c1.server();
    Thread.sleep(1000);
    c1.send();
 }
} 

class ServerThread implements Runnable{
    Client cl;
    public ServerThread(Client cl){this.cl = cl;}
    public void run(){
        BufferedReader in;
        Socket  socket = cl.getSocket();
        
        while(true){
            if(cl.isQuit()){return;}
            try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            char[]  buffer = new char[1024*1024*5];
            String lineStr = "";
            /*while((lineStr = in.readLine()) != null){    
                System.out.println(lineStr);
            }*/
            int len = in.read(buffer,0,buffer.length);
            System.out.print(new String(buffer,0,len));
            }catch(IOException e) {
                System.out.println("ServerThread Wrong");
                e.printStackTrace();
                return;
            }
        }
        
    }
}


class SendThread implements Runnable{
    Client cl;
    public SendThread(Client cl){this.cl = cl;}
    public void run(){
         PrintWriter out;
         Socket  socket = cl.getSocket();
        while(true){
            try {
                out = new PrintWriter(socket.getOutputStream(),true);
                BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
                String tmp = line.readLine();
                if(tmp.equals("quit")){
                    cl.quit(true);
                    return;
                }
                out.println(tmp);
            }catch(IOException e) {
                System.out.println("SendThread  Wrong");
            }
        }
        
    }
}