java套接字客户端_java – 使用套接字的客户端 – 服务器 – 客户端通信

博客内容描述了如何创建一个简单的聊天应用程序,其中客户端A可以通过服务器B向客户端C发送消息。目前的实现只能处理一对一的通信,即服务器接收到客户端的消息后回传给同一客户端。为了实现客户端间的消息转发,需要修改服务器代码以识别并转发不同客户端之间的消息。
摘要由CSDN通过智能技术生成

我正在构建一个小型聊天应用程序,其中客户端A希望通过服务器B向客户端C发送内容.首先是这个问题的正确方法??.我能够向服务器发送数据和从服务器接收数据,但它仅限于客户端.例如,如果客户端A向服务器B发送数据并且客户端C正在向服务器B发送数据,那么我可以将数据发送回A和C就像一个echo服务器.但我想要的是通过服务器B将来自客户端A的数据转发到客户端C.

以下是服务器代码:

public class Server {

public static void main(String[] args) {

int port = 666; //random port number

try {

ServerSocket ss = new ServerSocket(port);

System.out.println("Waiting for a client....");

System.out.println("Got a client :) ... Finally, someone saw me through all the cover!");

System.out.println();

while(true) {

Socket socket = ss.accept();

SSocket sSocket = new SSocket(socket);

Thread t = new Thread(sSocket);

t.start();

System.out.println("Socket Stack Size-----"+socketMap.size());

}

}

catch (Exception e) { }

}

}

class SSocket implements Runnable {

private Socket socket;

public SSocket(Socket socket) {

this.socket = socket;

}

@Override

public void run() {

try {

InputStream in = socket.getInputStream();

OutputStream out = socket.getOutputStream();

DataInputStream dIn = new DataInputStream(in);

DataOutputStream dOut = new DataOutputStream(out);

String line = null;

while (true) {

line = dIn.readUTF();

System.out.println("Recievd the line----" + line);

dOut.writeUTF(line + " Comming back from the server");

dOut.flush();

System.out.println("waiting for the next line....");

}

}

catch (Exception e) { }

}

}

客户端代码是:

public class Client {

public static void main(String[] args) {

int serverPort = 666;

try {

InetAddress inetAdd = InetAddress.getByName("127.0.0.1");

Socket socket = new Socket(inetAdd, serverPort);

InputStream in = socket.getInputStream();

OutputStream out = socket.getOutputStream();

DataInputStream dIn = new DataInputStream(in);

DataOutputStream dOut = new DataOutputStream(out);

BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Type in something and press enter. Will send it to the server and tell ya what it thinks.");

System.out.println();

String line = null;

while (true) {

line = keyboard.readLine();

System.out.println("Wrinting Something on the server");

dOut.writeUTF(line);

dOut.flush();

line = dIn.readUTF();

System.out.println("Line Sent back by the server---" + line);

}

}

catch (Exception e) { }

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值