[英]Server is not sending back an acknowledgment to Client
I have my server code below over here: 我在下面有我的服务器代码:
public void startServer() {
ServerSocket listener = selectUnusedPortFromRange(1024, 65535);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
String command = null;
while (true) {
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
command = in.readLine();
System.out.println("GOT HERE"); //Not being printed out
if (command != null && !"".equals(command)) {
if ("connection".equals(command)) {
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("success\n");
writer.flush();
}
}
}
}
}
}
t.start();
}
This is my client side: 这是我的客户端:
public void makeConnection() {
try {
Socket socket = new Socket(IP, PORT);
Writer writer = new PrintWriter(socket.getOutputStream(), true);
writer.write("connection\n");
BufferedReader socketRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = socketRead.readLine()) != null) {
if ("success".equals(str)) {
System.out.println("Successfully saved all hosts to: " + listOfHosts.get(i));
socketRead.close();
socket.close();
iStream.close();
writer.close();
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
On the client side after I create my socket to the connect to the server I write "connection" into the outputStream
of the socket and wait for an acknowledgement back from the server saying success. 在创建用于连接服务器的套接字后,在客户端,我将“连接”写入套接字的outputStream
中,并等待服务器返回确认成功的确认。 For some reason the connection is not being made to the server. 由于某种原因,未建立与服务器的连接。 In the server System.out.println("Got a connection from: " + socket.getLocalPort());
在服务器中System.out.println("Got a connection from: " + socket.getLocalPort());
this line is not being printed out. 该行没有被打印出来。
Is there something wrong that I am doing. 我在做错什么吗? I can't spot it. 我没发现 And I am not getting an exception thrown when I try to connect to my server. 当我尝试连接到服务器时,并没有引发异常。
1) Make sure you use the same port for both the Client and Server. 1)确保客户端和服务器使用相同的端口。 They must communicate over the same port. 他们必须通过同一端口进行通信。 It seems you may be using different ports currently. 看来您当前正在使用其他端口。
2) Make sure you actually start your server thread. 2)确保您确实启动了服务器线程。 As-is in your code above, you make a new Thread, but never start it. 在上面的代码中,按原样,您创建了一个新的Thread,但是从不启动它。 t.start()
must be called somewhere. t.start()
必须在某处调用。
3) If this is on your local machine, you may be better off using localhost
instead of the actual IP address. 3)如果在本地计算机上,则最好使用localhost
而不是实际IP地址。 Firewalls might treat your external IP differently. 防火墙可能会对您的外部IP有所不同。
4) Terminate your messages with a newline character, such as \\n
, so that your BufferedReader
can use it's readLine()
method. 4)用换行符(例如\\n
)终止消息,以便您的BufferedReader
可以使用它的readLine()
方法。 For good measure, also follow-up by flushing the writer's buffer, just in case the newline character didn't trigger that. 作为一种很好的措施,还可以通过刷新编写器的缓冲区进行后续操作,以防万一换行符未触发该操作。 writer.flush();
And lastly, make sure you terminate the JVM before trying to run your code again. 最后,请确保在尝试再次运行代码之前终止JVM。 Your code has not shutdown mechanism to un-bind the server from the port... so you may get an exception thrown telling you the port and/or address are already in use. 您的代码没有关闭机制来从端口取消绑定服务器...因此您可能会抛出异常,告诉您端口和/或地址已在使用中。 If that happens, either change ports, or kill the java process running in the background. 如果发生这种情况,请更改端口,或终止在后台运行的Java进程。
Here is your code, slightly modified to run on my system. 这是您的代码,经过略微修改后可以在我的系统上运行。 It's working as you might expect it to. 它正在按预期运行。 I tried to change as little as possible just to get it working on my system. 为了使它在我的系统上正常运行,我尝试了尽可能少的更改。 One note is, I hard-coded the port number into the server and client - that's not required, it was just convenient for me to test with: 需要注意的是,我将端口号硬编码到服务器和客户端中,这不是必需的,这对我进行测试很方便:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class Test {
public static void main(String[] args) throws IOException {
Test test = new Test();
test.startServer();
test.makeConnection();
}
public void startServer() throws IOException {
final ServerSocket listener = new ServerSocket(60001);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
String command = null;
while (true) {
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
command = in.readLine();
System.out.println("GOT HERE");
if (command != null && !"".equals(command)) {
if ("connection".equals(command)) {
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("success\n");
writer.flush();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
public void makeConnection() {
System.out.println("Making Connection");;
try {
Socket socket = new Socket("localhost", 60001);
Writer writer = new PrintWriter(socket.getOutputStream(), true);
writer.write("connection\n");
writer.flush();
BufferedReader socketRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = socketRead.readLine()) != null) {
if ("success".equals(str)) {
System.out.println("Successfully saved all hosts to: "); //+ listOfHosts.get(i));
socketRead.close();
socket.close();
//iStream.close();
writer.close();
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I was facing the exact same issue. 我正面临着完全相同的问题。 I overcame it by using an ACK mechanism (Wasn't my idea, it was suggested to me). 我通过使用ACK机制克服了这个问题(不是我的主意,有人向我建议)。 The idea is that client would make a request to server and keep the socket connection alive (and the ouput stream open) till server responds back an agreed ACK message over the same channel . 这个想法是客户端将向服务器发出请求,并保持套接字连接处于活动状态 (并且输出流打开),直到服务器在同一通道上响应已同意的ACK消息。 Once the client receives the ACK message, only then it would close the connection. 客户端收到ACK消息后,只有这样才能关闭连接。
Below is the code for Server :- 以下是服务器的代码:-
final ServerSocket listener = new ServerSocket(11111);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
String command = null;
while (true) {
System.out.println("About to accept");
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
StringBuilder str = new StringBuilder(inputStream.readUTF());
//command = in.readLine();
System.out.println("GOT HERE. Msg received : "+str);
if (str != null && !"".equals(str.toString())) {
command = str.toString();
if ("connection".equals(command)) {
System.out.println("Got connection message");
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("connection");
outputStream.close();
}
}
inputStream.close();
System.out.println("Done");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
});
t.start();
}
Client :- 客户:-
public void makeConnection() {
try {
System.out.println("In makeConnection");
Socket socket = new Socket("127.0.0.1", 11111);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("connection");
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
StringBuilder str;
do {
str = new StringBuilder(dataInputStream.readUTF());
} while (!str.toString().equals("connection"));
System.out.println("Successfully saved all hosts to: ");
outputStream.close();
dataInputStream.close();
socket.close();
outputStream.close();
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
A call to start the proceedings :- 要求启动程序的电话:-
public void start() throws IOException, InterruptedException {
System.out.println("Starting server");
startServer();
Thread.sleep(1000);
System.out.println("Starting connection");
makeConnection();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.