套接字不接受字符串
Socket won't accept the strings
这是我的代码:
public class EchoServer {
ServerSocket ss;
Socket s;
DataInputStream din;
DataOutputStream dout;
public EchoServer()
{
try
{
System.out.println("server started");
//ss = new ServerSocket(0);
//System.out.println("listening on port: " + ss.getLocalPort());
ss = new ServerSocket(49731);
s = ss.accept();
System.out.println(s);
System.out.println("connected");
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
Server_chat();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args) {
new EchoServer();
}
public void Server_chat() throws IOException {
String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in ));
do
{
System.out.println("enter a string");
str = br.readLine();
System.out.println("str " + din.readUTF());
dout.flush();
}
while(!str.equals("stop"));
}
}
我通过端口号验证了 49731 端口。 0 更早得到这个端口。
当我在 Netbeans 上 运行 上面的代码时,输出显示 "server started" 然后它继续 运行ning 即使它应该显示已连接和我提供的输入的其余部分。
And then it keeps on running even though it should show connected and
rest of the input I provide.
为什么要继续打印 'connected'?
s=ss.accept();
In this line you are: listens for a connection to be made to this socket and accepts it. The
method blocks until a connection is made.
accept
方法将等待连接到他的客户端。所以你需要提供一个连接到服务器的客户端。否则他会一直等下去!
有关如何在 java 中使用套接字的一些示例,请参阅 here and here。
有关 accept()
的更多信息,请阅读 here
这是我的代码:
public class EchoServer {
ServerSocket ss;
Socket s;
DataInputStream din;
DataOutputStream dout;
public EchoServer()
{
try
{
System.out.println("server started");
//ss = new ServerSocket(0);
//System.out.println("listening on port: " + ss.getLocalPort());
ss = new ServerSocket(49731);
s = ss.accept();
System.out.println(s);
System.out.println("connected");
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
Server_chat();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args) {
new EchoServer();
}
public void Server_chat() throws IOException {
String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in ));
do
{
System.out.println("enter a string");
str = br.readLine();
System.out.println("str " + din.readUTF());
dout.flush();
}
while(!str.equals("stop"));
}
}
我通过端口号验证了 49731 端口。 0 更早得到这个端口。
当我在 Netbeans 上 运行 上面的代码时,输出显示 "server started" 然后它继续 运行ning 即使它应该显示已连接和我提供的输入的其余部分。
And then it keeps on running even though it should show connected and rest of the input I provide.
为什么要继续打印 'connected'?
s=ss.accept();
In this line you are: listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.
accept
方法将等待连接到他的客户端。所以你需要提供一个连接到服务器的客户端。否则他会一直等下去!
有关如何在 java 中使用套接字的一些示例,请参阅 here and here。
有关 accept()
的更多信息,请阅读 here