Java服务器套接字响应

时间:2013-12-12 21:04:15

标签: java sockets client serversocket

我正在尝试创建一个简单的客户端/服务器套接字通信应用程序(聊天客户端)。我花了无数个小时看着如何解决这个仍然没有运气,我可以将消息发送到服务器,但我坚持将消息从服​​务器发送回客户端。

我相信问题是我在收到邮件之后从服务器收到邮件的方式,我删除了我所拥有的一个我无法工作的InputStreamReader。

(我提前为草率代码道歉)

Server.java

public class Server extends Thread {
@SuppressWarnings("unused")
private static Socket socket;
static int port = 1337;
static ObjectOutputStream output;

@SuppressWarnings("resource")
public static void main(String[] args) throws IOException{  
    ServerSocket ss = new ServerSocket(port);
    System.out.println("Server started on port: " + port);
    while(!Thread.interrupted()){
        try {  
            Socket clientSocket = ss.accept();
            DataInputStream dis = new DataInputStream(clientSocket.getInputStream()); 
            PrintStream output = new PrintStream(clientSocket.getOutputStream());
            String str = (String)dis.readUTF();
            String[] split = str.split("-");
            String subStringUsername = split[0];
            String subStringMessage = split[1];
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss a");
            String formattedTimestamp = sdf.format(date);
            System.out.println("Message from " + subStringUsername + ": " + subStringMessage + " - at " + formattedTimestamp);
            output.flush();

            output.println("Message received! Hello client!");
            System.out.println("Reply sent");
            output.flush();

            //TODO create new thread handle new users instead of Thread sleep
            //TODO chat commands and user ID / can't be existing user

            Thread.sleep(500);
        }
        catch(Exception e){
            System.out.println(e);
        } 
    }
}

getMessage.java

public class GetMessage extends Thread {    
    public void run(){
        while(true) {
            InputStreamReader be = new InputStreamReader();
        }
    }
}

这是我在getMessage类中留下的内容,因为我在挫折中删除了所有内容,我正在运行getMessage作为一个我不知道是最好的方法的线程。我已经尝试了10种方法从服务器获取消息仍然没有运气,如果有人能指出我正确的方向,我会非常感激。

2 个答案:

答案 0 :(得分:5)

readUTF阻塞直到它收到输入结束,并且应该只读取通过writeUTF方法传递的数据。

参考:进行更完整的讨论。

readUTF() causing Android app to hang

Also check out the docs

你可能想要替换

DataInputStream dis = new DataInputStream(clientSocket.getInputStream());

 BufferedReader reader = new BufferedReader(
        new InputStreamReader(clientSocket.getInputStream()));

 dis.readUTF();

String str = reader.readLine();

或者,如果您没有使用新行标记消息的结尾

char[] buffer = new char[1024];
int read = 0;
StringBuilder sb = new StringBuilder();

while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
    sb.append(buffer, 0, read);
    // conduct some test that when passes marks the end of message, then break;
}
reader.close();

String str = sb.toString().trim();

答案 1 :(得分:1)

请在刷新方法之后或者在完成刷新流出后放置output.close()。

此外,我会使用类似的东西来实现聊天应用程序。它还使用Java Swings来绘制客户端和服务器窗口。用它作为参考。格式化可能在这里有点草率。

这是我的客户代码:

public class Client
{
private Socket s;
private Scanner input;
private PrintWriter output;
private ChatFrame frame;
static String s1;

public Client( int port ) throws IOException 
{
    s = new Socket( "127.0.0.1", port );
    input = new Scanner(s.getInputStream());
    output = new PrintWriter(s.getOutputStream());

}
public static void main(String[] args) throws java.io.IOException
{
    System.out.println("Enter The port No. :");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String s = br.readLine();
    System.out.println("Enter Name : ");
    br = new BufferedReader(new InputStreamReader(System.in));
    s1 = br.readLine();
    final Client client = new Client(Integer.parseInt(s));
    EventQueue.invokeLater(new Runnable() 
       {
            public void run() {
            client.frame = new ChatFrame(client.output,s1);

            }
        });

    String ClientChat = "";
    while(true) 
    {
        if(client.input.hasNextLine()) 
        {
            ClientChat = client.input.nextLine();
            client.frame.Chat(ClientChat);                                
        }
    }
   }
 }
class ChatFrame 
{
    JFrame jf;
    JPanel jp;
    JTextArea jta1,jta2;
    JButton jb;
    public ChatFrame(final PrintWriter output, final String Name) 
       {
            jf = new JFrame();
            jf.setTitle(Name);
            jf.setSize(800,600);
            jp = new JPanel();
            jp.setBounds(0,0,800,600);
            jta1 = new JTextArea();
            jta2 = new JTextArea();
            jta1.setBounds(20,10,760,390);
                 jta1.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
            jta2.setBounds(20,420,550,100);
            jta2.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
            jb = new JButton("SEND");
            jb.setBounds(590,420,190,100);
            jp.add(jb);
            jp.add(jta1);
            jp.add(jta2);
            jp.setLayout(null);


    ActionListener Action = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
            String str = Name + " : " + jta2.getText();
            if(str.length() > 0) 
                {
                    output.println(str);
                    output.flush();
                    jta2.setText("");
                    jta2.grabFocus();
                }
        }
    };
    jb.addActionListener(Action);
    jf.add(jp);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setVisible(true);
    }
    public void Chat(String MSG) 
    {
            jta1.append(MSG + "\n");
            StringTokenizer st = new StringTokenizer(MSG,":");
            int flag = 0;
            if(st.hasMoreElements())
               {
                    if(st.nextElement() == "bye" && flag == 0)
                       {
                            jf.setVisible(false);
                            jf.validate();
                            System.exit(0);
                        }
                    flag = 1;
                }
       }
}

这是我的服务器代码:

public class MyServer
 {
    Hashtable<Socket,PrintWriter> output = new Hashtable<Socket,PrintWriter>();
    ServerSocket ss;
    Socket s;
    public void MakeConn()
       {
            try
               {
                    ss = new ServerSocket(1001);
                    while(true)
                    {
                        s = ss.accept();
                        System.out.println("Connection from " + s);
                        PrintWriter outMsg = new PrintWriter(s.getOutputStream());
                        output.put(s,outMsg);
                        new ServerThread(this,s);
                    }
                }
            catch(Exception E)
               {

                }
        }

    public void tellEveryOne(String msg) 
    {
        synchronized(output) 
        {
            Enumeration keys = output.keys();
            while ( keys.hasMoreElements() )
               {
                    Socket ss = (Socket)keys.nextElement();
                    PrintWriter outMsg = output.get( ss );
                    outMsg.println(msg);
                    outMsg.flush();
                }
        }
    }
    public void ConnectionClose(Socket socket) 
    {
        try 
           {
                output.remove(socket);
                socket.close();
           }
        catch(IOException e) 
           {

           }
    }
public static void main(String[] args)
{
    MyServer ms = new MyServer();
    ms.MakeConn();
}
}

class ServerThread extends Thread
   {
        MyServer server;
        Socket socket;

        public ServerThread(MyServer server, Socket socket) 
           {
                this.server = server;
                this.socket = socket;
                this.start();
            }
        public void run() 
           {
                try 
                   {
                        Scanner input = new Scanner(socket.getInputStream());
                        String inMsg;
                        String ByeMsg;
                        while(true) 
                           {
                                  if(input.hasNextLine()) 
                                   {
                                            inMsg = input.nextLine();
                                         System.out.println(inMsg);
                                         StringTokenizer st = new StringTokenizer(inMsg,":");
                                        int flag = 0;
                                         if(st.hasMoreElements())
                                           {
                                                if(st.nextElement() == "bye" && flag == 0)
                                                   {
                                                         input.close();
                                                         socket.close();
                                                         break;
                                                     }
                                                flag = 1;
                                            }
                                          server.tellEveryOne(inMsg);
                                    }
                            }
                    }
                catch(IOException E)
                   {
                    }
                finally 
                   {
                        server.ConnectionClose(socket);
                   }
            }

    }