java 服务器转发数据,求教java聊天工具服务器如何转发数据

Java codeimport 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");

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值