gpt4 book ai didi

Java套接字在连接到服务器2期间发送一些数据

转载 作者:行者123 更新时间:2023-12-02 00:34:22 25 4
gpt4 key购买 nike

Possible Duplicate:
Java socket sends some data during connection to server

我有两个非常非常简单的java程序——客户端和服务器。它们通过套接字建立连接。服务器从流中读取字符并将其打印到控制台。

import java.net.*;
import java.io.*;
import java.util.Date;
public class DataServerSIMS {
static final int LISTENING_PORT = 2002;
public static void main(String[] args) {
ServerSocket listener; //Checks the connection requests
Socket connection; //To interact with other progs
Reader incoming; //Stream
try {
listener = new ServerSocket(LISTENING_PORT);
TextIO.putln("Listening on port "+LISTENING_PORT);
while (true) {
connection = listener.accept();
try {
incoming = new InputStreamReader(connection.getInputStream());
while (true) {
int ch = incoming.read();
if (ch == 1 || ch == '\r')
break;
System.out.print((char)ch);
}
System.out.println();
incoming.close();
}
catch (IOException e) {
TextIO.putln("Error: "+e);
}//end try recieving data
}//end while
}
catch (Exception e) {
TextIO.putln("Sorry, the server has shut down.");
TextIO.putln("Error: "+e);
return;
}
}
}

客户端仅建立套接字连接。

import java.net.*;
import java.io.*;
import java.util.Date;
public class TempClientSIMS {
//static final int LISTENING_PORT = 32007;
static final int LISTENING_PORT = 2002;
public static void main(String[] args) {
ServerSocket listener; //Checsk the connection requests
Socket connection; //To interact with other progs
Socket connectionToServer = null; //Socket
Reader incoming; //Stream
try {

TextIO.putln("Localhost connects to:"+LISTENING_PORT);

connectionToServer = new Socket ("localhost", 2002);

TextIO.putln("Connected ");

long i=0;
while (i<2000000000) {
i++;
}


}
catch (Exception e) {
TextIO.putln("Sorry, the server has shut down.");
TextIO.putln("Error: "+e);
return;
}
}


}

客户端不向服务器发送任何数据。

我在我的电脑上启动了这两个程序。客户端打印:

Localhost connects to:2002
Connected
Press any key to continue . . .

服务器打印:

Listening on port 2002
FdsfsdfsError: java.net.SocketException: Connection reset

很清楚为什么这个字符串“Error: java.net.SocketException: Connection reset”会打印在服务器的控制台上。但我不知道这是什么意思:“Fdsfsdfs”?我可以阻止打印这个字符串“Fdsfsdfs”吗?

最佳答案

您不使用 Reader 检查流结束。将该检查添加到您的代码中。

http://docs.oracle.com/javase/1.4.2/docs/api/java/io/Reader.html#read%28%29

                 //Try this 
while (true) {
int ch = incoming.read();
if (ch == 1 || ch == '\r'||ch == -1)
break;
System.out.print((char)ch);
}

关于Java套接字在连接到服务器2期间发送一些数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8220451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com