通过指定的用户ID将消息从服​​务器发送到套接字

时间:2013-09-19 08:34:45

标签: java multithreading sockets client-server

我是Java的新手,我正试图找出一些问题。

我希望能够通过指定他的ID从服务器向客户端发送消息。 我想到了这一点,我认为如果我为每个连接并将其放入PrintWriter数组的客户端创建一个PrintWriter会是一个好主意,但这似乎不起作用,希望你们能够/将帮助我。

一些方法名称是我母语希望不是问题。

package homeControl;

import java.net.*;
import java.util.Scanner;
import java.io.*;
import java.awt.*;

public class Server {
    String sporocilo = null;
    int id = 0;
    ServerHandler handler = new ServerHandler();

    public void sprejmiPovezavo() {
        try {
            ServerSocket svrSock = new ServerSocket(5000);
            Socket klientSocket = svrSock.accept();

            new Thread(new ServerHandler(klientSocket));
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server svr = new Server();
        svr.sprejmiPovezavo();
    }
}

服务器处理程序代码:

package homeControl;

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

public class ServerHandler implements Runnable {
Socket klientSocket;
static int userCounter = 0;
static int selectedId = 0;
BufferedReader reader;
PrintWriter writer;
PrintWriter[] writerHolder = new PrintWriter[10];

outputHelper out = new outputHelper();  

public ServerHandler(Socket klientSocket) throws IOException {
    userCounter++;
    this.klientSocket = klientSocket;
    writer = new PrintWriter(this.klientSocket.getOutputStream());
    writerHolder[userCounter] = writer;

    InputStreamReader inReader = new InputStreamReader(this.klientSocket.getInputStream());
    reader = new BufferedReader(inReader);

    out.frameOutput(this.klientSocket.getInetAddress().toString(), "Server sprejel povezavo:");

    selectedId = userCounter;
    posljiSporocilo("wassup");
}

public ServerHandler() {
    // Do not launch the main Constructor
}

public void run(){
    String inMessage = null;
    try{
        while((inMessage = reader.readLine()) != null) {
            System.out.println("Server Sprejel: " + inMessage);
        }
    } catch(IOException ex){
        ex.printStackTrace();
    }   
}

public  void selectId(int id){
    selectedId = id;
}

public void posljiSporocilo(String sporocilo){
    writerHolder[selectedId].println(sporocilo + "\n");
    writerHolder[selectedId].flush();
}
}

1 个答案:

答案 0 :(得分:0)

根据您编写的内容,只有一个客户端可以连接到服务器。 以下更改允许您接受多个客户端。服务器接受并提供连接请求,然后继续接受其他请求。

ServerSocket svrSock;
try{
    svrSock = new ServerSocket(5000);
} catch(IOException e){
    e.printStackTrace();
    System.exit(-1);
}
while(true){
   try {
        Socket klientSocket = svrSock.accept();
        new Thread(new ServerHandler(klientSocket));
   } catch(IOException ex) {
        ex.printStackTrace();
   }
}