使用套接字向特定客户端发送消息

时间:2016-04-29 20:45:30

标签: java

我有2个班级

 public class ServerStart implements Runnable
    {
        @Override
        public void run() 
        {
            try
            {
                serverSock = new ServerSocket(2101);
                while (true) 
                {
                    sock = serverSock.accept();
                    System.out.println(sock);
                    clients.put(sock.getPort(),sock);
                    HandleMultipleClients hmc=new HandleMultipleClients();
                    hmc.messagetospecificclients(String ipaddress,String choice)
                }

第二节课是

public class HandleMultipleClients
{

    Socket soc;
    ServerSocket serverSock;
    DataOutputStream dos;
    DataInputStream dis;
    public HandleMultipleClients()
    {

    }
    public void messagetospecificclients(String ipaddress,String choice) throws IOException, InterruptedException
    {
        System.out.print(ipaddress+"\n"+choice);
        for (Iterator<Integer> iter = clients.keySet().iterator(); iter.hasNext(); )
        {
            System.out.print("ok1");
            int key = iter.next();
            java.net.Socket client = clients.get(key);
            InetAddress zee = client.getInetAddress();
            String s = zee.getHostAddress();
            System.out.print(s);
            if (zee.getHostAddress().equals(ipaddress))
            {
                System.out.print("ok2");
                dos =new DataOutputStream(client.getOutputStream());
                dos.writeUTF(choice);
           }

当我向第一类添加客户端时,如何通过第二类函数的循环,即messagetospecificclients(String ipaddress,String choice),请帮助我。我的代码应该像我应该将客户端添加到第一类并且应该遍历第二类中的for循环

1 个答案:

答案 0 :(得分:0)

我会重组代码。分离套接字服务器的机制代码和返回数据的操作。可以从messageToSpecificClient方法启动返回数据代码。您可以启动整个班级或其他任何内容。 我没有运行它,但它应该运行。 关于这段代码的另一个警告是,它会遇到一些unicode的问题。 因此,如果这符合您的要求,则需要对其进行更改。

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class MultiThreadServer implements Runnable
{
    Socket  csocket;

    MultiThreadServer(Socket csocket)
    {
        this.csocket = csocket;
    }

    public static void main(String args[]) throws Exception
    {
        ServerSocket ssock = new ServerSocket(1234);
        System.out.println("Listening");
        while (true)
        {
            Socket sock = ssock.accept();
            System.out.println("Connected");
            new Thread(new MultiThreadServer(sock)).start();
        }
    }

    public void run()
    {
        PrintStream pstream = null;
        InputStream input = null;
        try
        {
            pstream = new PrintStream(csocket.getOutputStream());
            input = csocket.getInputStream();
            String stringFromClient = readFromInputStream(input);
            String response = messageTosSpecificClients(stringFromClient);
            pstream.write(response.getBytes());
        }
        catch (IOException e)
        {
            System.out.println(e);
        }
        finally
        {
            if (pstream != null)
                try
                {
                    pstream.close();
                }
                catch (Throwable t)
                {
                }
            if (input != null)
                try
                {
                    input.close();
                }
                catch (Throwable t)
                {
                }
            if (csocket != null)
                try
                {
                    csocket.close();
                }
                catch (Throwable t)
                {
                }
        }
    }

    String readFromInputStream(InputStream inputStream) throws IOException
    {
        int ch;
        StringBuilder sb = new StringBuilder();
        while ((ch = inputStream.read()) != -1)
            sb.append((char) ch);
        return sb.toString();
    }

    public String messageTosSpecificClients(String choice) throws IOException
    {
        String ipaddress = "127.0.0.1";

        String retData = "General Return String";
        System.out.print(ipaddress + "\n" + choice);
        InetAddress zee = csocket.getInetAddress();
        String s = zee.getHostAddress();
        System.out.print(s);
        if (zee.getHostAddress().equals(ipaddress))
        {
            retData = "Specific Return String";
        }
        return retData;
    }
}