Java Socket Chat,有些消息没有发送

时间:2014-03-25 01:38:52

标签: java sockets chat

我最近开始学习套接字和其他网络东西这样的工作,我用GUI做了一个简单的聊天程序,它有点工作,问题是如果命令消息发送到服务器客户端必须放相同消息两次,如果服务器发送消息,客户端必须回复一次。

继承我的客户端/服务器类:

package org.codingllamas.Chat;

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

import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTML;

public class SC {

static Socket clientSocket;
static BufferedReader inFromServer;
static DataOutputStream outToServer;

public static void clientSetup(int port,String ip) throws IOException, BadLocationException {
     String modifiedSentence;
     Start.kit.insertHTML(Start.doc,Start.doc.getLength(),"<b>Connected to </b>" + ip + ":" + port + "<br>",0,0,HTML.Tag.B);
     while (true) {
     ///BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
     clientSocket = new Socket(ip,port);
     outToServer = new DataOutputStream(clientSocket.getOutputStream());
     inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
     modifiedSentence = inFromServer.readLine();     
     //System.out.println(modifiedSentence);
     Start.kit.insertHTML(Start.doc,Start.doc.getLength(),"<b>Server: </b>" + modifiedSentence + "<br>",0,0,HTML.Tag.B);
     //clientSocket.close();
     }
}

public static void clientSend(String msg) throws IOException, BadLocationException{
    outToServer.writeBytes(msg + "\r");
    outToServer.flush();
    Start.kit.insertHTML(Start.doc,Start.doc.getLength(),"<b>You: </b>" + msg + "<br>",0,0,HTML.Tag.B);
}

static ServerSocket welcomeSocket;
static Socket connectionSocket;
static BufferedReader inFromClient;
static DataOutputStream outToClient;

public static void serverSetup(int port) throws Exception {
    String clientSentence;
    welcomeSocket = new ServerSocket(port);
    Start.kit.insertHTML(Start.doc,Start.doc.getLength(),"<b>Server Started on port: " + port + "</b><br>",0,0,HTML.Tag.B);
    while(true){
       connectionSocket = welcomeSocket.accept();
       inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
       clientSentence = inFromClient.readLine();
       outToClient = new DataOutputStream(connectionSocket.getOutputStream());

       Start.kit.insertHTML(Start.doc,Start.doc.getLength(),"<b>Parther: </b>" + inFromClient.readLine() + "<br>",0,0,HTML.Tag.B);
    }
}

public static void serverSend(String msg) throws IOException, BadLocationException {
    //DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
    outToClient.writeBytes(msg + "\r");
    outToClient.flush();

    Start.kit.insertHTML(Start.doc,Start.doc.getLength(),"<b>You: </b>" + msg + "<br>",0,0,HTML.Tag.B);
}
}

一张图片:

enter image description here

提前致谢。

1 个答案:

答案 0 :(得分:1)

  1. 请勿使用DataOutputStream,请使用BufferedWriter.
  2. 不要为每个modifiedSentence?创建一个新套接字:在客户端的生命周期中使用单个Socket,并循环读取行,并在获得null时关闭套接字。
  3. 每个accept():不要从客户端读取一行,启动一个新线程来读取客户端现在所做的行。