我試圖從Socket的InputStream讀取一個字符串變量,然後打印它。但是,不知何故,這不能正常工作。 receivedText
僅在客戶端斷開連接時纔打印到控制檯。我的代碼有什麼問題?從套接字讀取到字符串
public xClient(Socket socket)
{
Thread receiver = new Thread(){
public void run()
{
String receivedText = "";
while(socket.isConnected())
{
try {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while((line = input.readLine()) != null)
{
receivedText += line;
}
if(!receivedText.equals(""))
{
System.out.println(receivedText);
receivedText = "";
}
Thread.sleep(10);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
receiver.start();
}
主要方法:
ServerSocket socket = new ServerSocket();
socket.bind(new InetSocketAddress("127.0.0.1",9200));
Thread accepting = new Thread(){
public void run()
{
while(true)
{
try {
Socket received = socket.accept();
new xClient(received);
System.out.println("OK");
Thread.sleep(10);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
accepting.start();
但它是如何工作的?你啓動一個serversocket,然後等待在服務器上連接,然後創建一個客戶端,該客戶端應該首先創建一個連接?你是否從其他客戶端或telnet啓動連接到服務器? – alobodzk
xClient類用於偵聽連接到服務器的客戶端。這不是一個客戶類。 – farukdgn