使用DataOutputStream将消息写入客户端套接字仅在关闭Client Socket后发送到服务器套接字为什么? [英] Writing messages to client socket using DataOutputStream to Server Socket only sent after closing the Client Socket why?

查看:138
本文介绍了使用DataOutputStream将消息写入客户端套接字仅在关闭Client Socket后发送到服务器套接字为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Java编写了一个Socket-Client编程。我正在使用DataOutputStream将消息发送到服务器套接字。有时,DataOutputstream上的写入消息未发送到ServerSocket。我认为这是因为我发送消息后没有冲洗。我这样做但没用。如果我终止类执行,那么只有我从ServerSocket接收消息。

I had a Socket-Client programming in Java . I am using DataOutputStream to send messages to the Server Socket . Sometimes writed messages on DataOutputstream was not sent to the ServerSocket . I think it's due to i am not flushing after sent message . I do this but no use . If I terminate the class execution then only I receive messages from ServerSocket .

我的代码:

public class LoggingClient {


LinkedBlockingQueue<byte[]> messages = new LinkedBlockingQueue<byte[]>();

public static LoggingClient clientObj;

/*
 * waiting 2 seconds for connecting centralized log server . If it's not reachable writing log's in local machine
 * this log's will be collected on eclipse restart.
 */
public static final int SOCKET_TIMEOUT = 2000;
/**
 * Server which the log server is currently running.
 */
public static final  String SERVER = "bharathi";
/**
 * Port which the log server is running.
 */
public static final int PORT = 10000;

/**
 * Client socket used to connect the server .
 */
Socket client = null;

public static Logger logger = Logger.getLogger(LoggingClient.class.getName());


/**
 * Used to write given logs into client output stream.
 */
DataOutputStream out = null;

public boolean isConnected = false;

/**
 * Used for preventing instaniate LoggingClient without calling getInstance method.
 */
private LoggingClient(){

}

/**
 * Clear's the socket and initialize new socket .
 */
public void init(){
try{
    clear();
    client = new Socket();
        client.setTcpNoDelay(true);
    client.connect(new InetSocketAddress(SERVER,PORT),SOCKET_TIMEOUT); //trying to make connection within two seconds.
    out = new DataOutputStream(client.getOutputStream());
    isConnected = true;
}catch(Exception e){
    isConnected = false;
}
}

public static LoggingClient getInstance(){
if(clientObj == null){
    clientObj = new LoggingClient();
}
return clientObj;
}

public void clear(){
try{
    if(out != null){
    out.close(); //if we call close method it invokes flush and then closes the DataOutputStream.
    }

    if(client != null){
    client.close();
    }
}catch(Exception e){
    logger.log(Level.INFO,"Error while closing connection , reason {0}",e);
}finally{
    try{
    client.close();
    out.close();
    }catch(Exception e){

    }
    isConnected = false;
}
}


/**
 * Adding this message into a queue . Scheduled thread will get this logs and push into central logging server.
 * @param message
 */
public synchronized void write(byte[] message){
if(!isConnected){ //has connection.
    init();
}
messages.add(message); //adding message to this queue . Background thread will collect the log message and sent it to the central log server.
}

/**
 * Sending logs into central log server . If it's not reachable write into local machine.
 * @param message
 */
public void sendLog(byte[] message){
try {
    out.write(message);
    out.flush();
} catch (Exception e) {
    writeInLocalMachine(localLoggingPath, message); //in case of failure writing logs in local machine . Sync this logs when restart of eclipse.
}
}

/**
 * Writing log's into his machine this log will be synced on plugin startup.
 * @param file - File path.
 * @param message - Message  to log.
 */
public static void writeInLocalMachine(String file, byte[] message) {
FileOutputStream fileWriter = null;
File f = new File(file);
try {
    if(!f.exists()){
    f.createNewFile();
    }
    fileWriter = new FileOutputStream(file, true);
    fileWriter.write(message);
    fileWriter.flush();
} catch (Exception e) {
   logger.log(
        Level.WARNING,
        "This may be due to given file not found in system , reason {0}",
        e);
} finally {
    try{
    fileWriter.close();
    }catch(Exception e){

    }
}
}

/**
 * @return - Recently received message from queue . Returns null if it's empty.
 */
public byte[] getMessage(){
return messages.poll(); //returns the head element and deletes it.
}

}

测试用于将消息发送到服务器套接字的java类。

Testing java class for sending messages to server socket .

public class LogTest implements Runnable {

public static final String LINE_SEPARATOR = System.getProperty("line.separator");


@Override
public void run() {
while(true){
    try{
        LoggingClient client = LoggingClient.getInstance();
        byte[] message = client.getMessage();
        if(message != null){
            client.sendLog(message);
        }
    }catch(Exception e){

    }
}
}

public static void startSending(){
for(int i=0;i<10000;i++){
    String msg = "msg number" + i+LINE_SEPARATOR;
    LoggingClient.getInstance().write(msg.getBytes());
}
}

public static void main(String args[]){
    LoggingClient c = LoggingClient.getInstance();
    System.out.println("START TIME " + System.currentTimeMillis());
    Thread t = new Thread(new LogTest(),"LOG MESSAGER");
    t.start();
    startSending();
    System.out.println("END TIME " + System.currentTimeMillis());
}

已发送的消息将存储在一个文件中。

Sent messages will be stored in a file .

输出:

START TIME 1340815857896
END TIME 1340815858063

完成将消息放入队列。无限while循环将负责将日志发送到服务器套接字。

Finished putting messages into the queue . The infinite while loop will take care of sending logs into the server socket .

存储在文件中的内容是0字节为什么? 。如果我停止运行课程,我会收到发送消息的原因吗?

Content Stored In file is 0 bytes why ? . If i stop running class I receive sent messages why?

推荐答案

你发布了太多代码,但在100分中有99次在流/程序关闭您的问题后您只看到数据的情况是您在写入数据后永远不会刷新数据

You have posted too much code, but 99 times out of 100 in these cases where you only see the data after the stream / program has closed your problem is that you are never flushing the data after it is written

这篇关于使用DataOutputStream将消息写入客户端套接字仅在关闭Client Socket后发送到服务器套接字为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆