在Java Socket Client-Server中获取“连接到主机丢失”

时间:2015-08-03 15:40:46

标签: java sockets client localhost

对于服务器,我必须将提供的代码更改为多线程服务器。对于客户端,我已更改它以使其从文本文件中读取数据。

到目前为止,我已经设法编译,但是当在客户端运行时,它不仅提供奇数符号,而且最后它说“连接主机丢失”。我已经尝试更改套接字号,同样的问题仍然存在。

所以这就是它的样子:

  

¼Ýsr♥Car'3▼3çw3û☻♦DmileageLmodelt↕Ljava/郎/字符串; Lownerq〜☺L

     
    

registrationq〜☺xp@     “Honda Civic”“John S”q~square~ @@ t-sq~ @Òêt                                 “Vokswagen”t“Maria B”q~

  
     

与主机丢失的连接。

这是我的服务器代码:

//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();
    }
  }
}

对于客户

//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
}

我是编程的新手,所以请帮帮我。

1 个答案:

答案 0 :(得分:0)

您的问题似乎在这里:

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

您正在使用所有文本行,一旦完成,oisFromServer将返回null。

要解决此问题,我建议您使用套接字中的原始InputStream和InputStream.read()。此外,曾几何时我为这种阻塞阅读编写了一个实用工具类。请参阅DataFetcher及其在同一项目包中的依赖项