JAVA - Sockets :: readline()没有做任何事情

时间:2014-07-06 10:02:00

标签: java sockets tcp readline serversocket

我创建了一个网络类,我打开一个套接字而不是向它发送请求。

班级:

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

public class Network implements Runnable {
    private boolean isHost = false;

    private int hostPort = 19250;
    private int clientPort = 19251;
    private String host = "127.0.0.1";
    private String name = "";

    private ServerSocket ownServer = null;
    private Socket otherServer = null;
    private DataOutputStream outToServer = null;
    private BufferedReader inFromServer = null;
    private boolean isConnected = false;

    /**
     * Konstruktor -
     */
    Network(String name) {
        this.name = name;
        this.findHost();
        // if no host exists, become host itself
        if (this.isHost == false) {
            // host da -> become client
            System.out.println(this.name + ": host found");
            try {
                ownServer = new ServerSocket(this.clientPort);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // kein host da -> become host
            System.out.println(this.name + ": no host found");

            try {
                ownServer = new ServerSocket(this.hostPort);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * connect() - versucht mit anderem server zu connecten fals dies noch nicht
     * geschehen ist
     * 
     * @return true/false
     */
    public boolean connect() {

        if (this.isConnected == false) {
            try {
                if (this.isHost) {
                    otherServer = new Socket(this.host, this.clientPort);
                } else {
                    otherServer = new Socket(this.host, this.hostPort);
                }
            } catch (IOException e) {
                //System.out.println(this.name + ": connect failed");
                this.isConnected = false;
                return false;
            }
        }

        try {
            outToServer = new DataOutputStream(otherServer.getOutputStream());
            inFromServer = new BufferedReader(new InputStreamReader(
                    otherServer.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //System.out.println(this.name + ": connect sucess");
        this.isConnected = true;
        return true;
    }

    /**
     * findHost() - schaut ob ein Host existiert
     * 
     * @return true/false
     */
    private boolean findHost() {
        Socket hostSocket;
        try {
            hostSocket = new Socket(this.host, this.getHostPort());
            DataOutputStream outToServer = new DataOutputStream(
                    hostSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(
                    new InputStreamReader(hostSocket.getInputStream()));
            outToServer.writeBytes("uHost?\n");// Fragen ob Host ist
        } catch (Exception e) {
            this.isHost = true;
            return false; // Keine Connection aufgebaut => kein Host vorhanden
        }
        this.isHost = false;
        return true; // Es gibt schon einen Host
    }

    public int getClientPort() {
        return this.clientPort;
    }

    public int getHostPort() {
        return this.hostPort;
    }

    public boolean getIsHost() {
        return this.isHost;
    }

    /**
     * sendToOther() - schickt daten an anderen Server
     * 
     * @param data
     */
    public void sendToOther(String data) {
        this.connect();
        try {
            this.outToServer.writeBytes(data);
            this.outToServer.writeBytes("\n"); //new Line
            this.outToServer.flush();
            System.out.println(this.name + ": " + data
                    + " :: send to other server");

        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            this.outToServer.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        // listen to income
        String line = "";
        try {
            while (true) {
                System.out.println(this.name + ":111");
                while ((line = inFromServer.readLine())!= null) {
                    System.out.println(this.name + ":222");
                    System.out.println(this.name + ":recieved: " + line);
                }
                System.out.println(this.name + ":333");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void readAndDo(String data) {
        System.out.println(this.name + ": data recieved: " + data);
    }

}

主要方法:

public class Application {

    public static void main(String[] args) {
        Network t1net=new Network("ss1");
        Network t2net=new Network("ss2");
        t1net.connect();
        t2net.connect();


        t1net.sendToOther("some text1");
        t2net.sendToOther("sometext2");



        Thread t1 = new Thread( t1net );
        t1.start();


        Thread t2 = new Thread( t2net );
        t2.start();
    }

}

控制台:

ss1: no host found
ss2: host found
ss1: some text1 :: send to other server
ss2: sometext2 :: send to other server
ss2:111
ss1:111

netstat -a:

  TCP    127.0.0.1:19250        49on41PCX:54538        HERGESTELLT
  TCP    127.0.0.1:19250        49on41PCX:54540        HERGESTELLT
  TCP    127.0.0.1:19251        49on41PCX:54539        HERGESTELLT
  TCP    127.0.0.1:49156        49on41PCX:0            ABHÖREN
  TCP    127.0.0.1:54538        49on41PCX:19250        HERGESTELLT
  TCP    127.0.0.1:54539        49on41PCX:19251        HERGESTELLT
  TCP    127.0.0.1:54540        49on41PCX:19250        HERGESTELLT

问题是,readline() - 命令中的Network.run()块。数据已发送,从未收到过。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您以错误的方式使用了套接字。

ss:ServerSocket

s:套接字

您首先在两个主题上创建了两个ss,并使两个s连接到初始ss。这样ss1绑定到s2ss2绑定到s1。并且您仅从s1s2实现了输入和输出。因此,如果您从s1撰写,则不会进入s2。实际上,您需要从ss2创建另一个接受连接的套接字。与ss1相同。我希望你明白我的观点

实际上你应该只为主机创建一个ss。然后:

  

socketHost = ss.accept();

     

socketClient = new Socket(host,port);

现在,您可以使用这两个套接字通过其I / O流相互通信。

简而言之,您之前已经建立了两个联系ab。您在一个线程上从a发送和接收,并在第二个线程上从b发送和接收数据。

只需查看一些简单套接字I / O的教程,您就会明白。

编辑:请参阅http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html中的EchoClient.java和EchoServer.java