简体   繁体   English

Java Socket Client-Server中的“主机连接丢失”

[英]Getting “connection to host lost” in Java Socket Client-Server

For the server I have to alter the provided code into a multi-threaded server. 对于服务器,我必须将提供的代码更改为多线程服务器。 For the client I have alter to it to make it read data from a text file. 对于客户端,我对其进行了更改,以使其从文本文件读取数据。

So far I've managed to compile but when running on the client side it not only gives odd symbols but in the end it says "connection host lost". 到目前为止,我已经设法进行了编译,但是当在客户端运行时,它不仅给出奇数符号,而且最后还说“连接主机丢失”。 I've tried changing the socket number the same problem persists. 我尝试更改套接字号,但同样的问题仍然存在。

So this is what it looks like: 这就是它的样子:

¼Ýsr♥Car´3▼3çw3û☻♦DmileageLmodelt↕Ljava/lang/String;Lownerq~☺L ¼Ýsr♥Car´3▼3çw3û☻♦DmileageLmodelt↕Ljava/ lang / String; Lownerq〜☺L

registrationq~☺xp@ "Honda Civic""John S"q~sq~@@t-sq~@Òêt "Vokswagen"t "Maria B"q~ 注册q〜☺xp@“本田思域”“ John S” q〜sq〜@@ t-sq〜@Òêt“大众汽车” t“玛丽亚B” q〜

Connection to host lost. 与主机的连接丢失。

This is my code for server: 这是我的服务器代码:

//a simple client/server application: car registration
//a SERVER program that uses a stream socket connection to exchange objects

import java.net.*;
import java.io.*;

public class CarsServer {

  public static void main(String[] args) throws IOException{

    ServerSocket serverSocket = null;; // TCP socket used for listening

    try {
      /* step 1: create a server socket port number: 8000 */
      serverSocket = new ServerSocket(5200);
      int i = 0;

      for(;;){
        /* setp 2: listen for a connection and create a socket */

        System.out.println("*** this server is going to register the cars ***");
        System.out.println("listening for a connection...");

        Socket clientSocket = serverSocket.accept();
        System.out.println("Spawning " + i++);
        new CarsClient(clientSocket, i).start();
      }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        /* step 5: close the connection to the client */
        System.out.println("*** the server is going to stop running ***");
        serverSocket.close();
    }
  }
}

And for Client 对于客户

//a simple client/server application that exchanges OBJECTS
//a CLIENT program that uses a stream socket connection to exchange objects

import java.net.*;
import java.io.*;

class CarsClient extends Thread{

    private Socket incoming;
    private int client;

    public CarsClient(Socket i, int c){
        this.client = c;
        this.incoming = i;
    }

    public void run(){
        try {
          /*
           * step 2: connect input and output streams to the socket
           */
          BufferedReader oisFromServer = new BufferedReader(new FileReader("Cars.txt"));

          ObjectOutputStream oosToServer = new ObjectOutputStream(incoming.getOutputStream());

          System.out.println("I/O streams connected to the socket");

      /*
       * step 3: communicate with the server
       */
        Car[] cars = new Car[3];
        int n = 0;
        String[] l;
        String line;
        while((line = oisFromServer.readLine()) != null){
           l = line.split(", ");
            try {
                // receive an object from the server
                cars[n] = new Car(l[0], l[1], Integer.parseInt(l[2])); // casting!

                // send an object to the server
                oosToServer.writeObject(cars[n]);
                //oosToServer.flush();
                System.out.println("\n### send this car to the server for registration:\n" + cars[n]);

                System.out.println("\t###### the car returned by the server:\n"+ cars[n]);
                n++;
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                }
            } catch (EOFException eof) {
                System.out.println("The server has terminated connection!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
          /*
           * step 4: close the connection to the server
           */
          System.out.println("\nClient: closing the connection...");
          oosToServer.close();
          oisFromServer.close();
          incoming.close();
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
        System.out.println("the client is going to stop runing...");
    } // end run
}

I'm new to programming so please help me out. 我是编程新手,所以请帮帮我。

It appears that your issue is here: 您的问题似乎在这里:

while((line = oisFromServer.readLine()) != null){

You are consuming all the lines of text, and once that's done, oisFromServer is going to return null. 您正在消耗所有文本行,一旦完成,oisFromServer将返回null。

To solve this, I recommend you use the raw InputStream and InputStream.read() from the socket. 为了解决这个问题,我建议您使用套接字中的原始InputStream和InputStream.read()。 Also, once upon a time I wrote a utility class for this kind of blocking reading. 同样,很久以前我为这种阻塞读取编写了一个实用程序类。 See DataFetcher , and its dependencies in the same project package 请参见DataFetcher及其在同一项目包中的依赖项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM