簡體   English   中英

是否可以同時讀取和寫入java.net.Socket?

[英]Is it possible to simultaneousy read from and write into a java.net.Socket?

是否可以同時從套接字讀取和寫入? 我有一個不斷讀取套接字的線程。 由於只有一個線程從套接字讀取,因此讀取操作是線程安全的。 現在我有許多線程(比如100)寫入套接字。 因此很明顯我通過做這樣的事情來使寫操作線程安全,

package com.mysocketapp.socketmanagement;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketManager {

    private Socket socket = null;

    private InputStream inputStream = null;

    private OutputStream outputStream = null;

    public SocketManager() {
        socket = new Socket("localhost", 5555);
        //server's running on same machine on port 5555
        inputStream = socket.getInputStream();

        outputStream = socket.getOutputStream();
    }

    public void writeMessage(byte[] message) throws IOException {

        synchronized (SocketManager.class) {

            if (message != null) {
                outputStream.write(message);
            }
        }
    }

    public byte[] readMessage() throws IOException {
        byte[] message = new byte[10]; //messages are of fixed size 10 bytes
        inputStream.read(message);
    }
}

現在我有一個不斷調用readMessage()函數的線程(在while循環中)。 據我所知,如果要讀取的套接字上沒有消息,則語句inputStream.read(message)將等待消息。

我想知道對outputStream.write(message);是否安全outputStream.write(message); inputStream.read(message); 正在執行中

是的,套接字是雙向的並且啟用全雙工通信,在執行(在不同線程上)同時讀取和寫入時沒有問題。

擁有多個寫線程沒有問題。 您可以在套接字實例而不是SocketManager類上進行同步。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM