java中的套接字帮助

时间:2014-09-21 17:02:29

标签: java sockets

我看了很多例子并问了几个人,但似乎没有人能够告诉我在我的监听插座上我做错了什么。请帮忙。

我正在制作一个程序,从3个文件读取,然后在线程中的套接字中发送数据。 这是我做过的每件事

public class Main {

    public static void main(String[] args) throws Exception{
    //making all threads for A,B and C
    Thread T_A = new Thread(new threads ("A"));
    Thread T_B = new Thread(new threads ("B"));
    Thread T_C = new Thread(new threads ("C"));
    //starting the threads for A,B and C
    T_A.start();
    T_B.start();
    T_C.start();
    }
}
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class threads implements Runnable {
        //making temps
        String name;
        int listen;
        int send;
        String line;
        BufferedReader reader;
        BufferedReader input;
        boolean Listening=false;
        boolean Sending=false;
        PrintWriter output;
        ServerSocket node_listen=null;
        Socket node_send=null;
        Socket node_rev=null;

        public threads(String x){
            //name of thead A,B or C
            name=x;                
        }

        @Override
        public void run(){
        try{
            //openinng the conf file for thread
            reader = new BufferedReader(new FileReader("conf" + name + ".txt"));
            //this is for node A because it only sends info does not get info
            if(name.equals("A")==true){
                //making a socket to send on
                System.out.println("Node " + name + " is starting");
                send = Integer.parseInt(reader.readLine());
                for(int temp=0;temp!=5;temp++)
                {
                    temp=Checker(temp);
                }
            }
            //this is for node B becuase it sends and gets info
            else if(name.equals("B")==true){
                //getting ports for send and listen
                listen = Integer.parseInt(reader.readLine());
                send = Integer.parseInt(reader.readLine());
                System.out.println("Node " + name + " is starting");
                Listening=setUpListen();                
                for(int temp=0;temp!=5;temp++)
                {
                    temp=Checker(temp);
                }
            }       
            //node C only gets info
            else if(name.equals("C")==true){
                //geting listen port
                listen = Integer.parseInt(reader.readLine());
                System.out.println("Node " + name + " is starting");
                Listening=setUpListen();
            }
            //sends and gets data until it has no more to send or get
            while(Listening==true || Sending== true)
            {
                //while it needs to get data and was a node that gets data
                if(Listening==true)
                {
                    Listen();
                }
                //Has not sent terminate yet and is a sending node
                if(Sending==true)
                {
                    Send();
                }
            }
        }
        catch(IOException | NumberFormatException e)
        {
            System.out.println(e);
        }   
        catch (InterruptedException ex)
        { 
                Logger.getLogger(threads.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Node " + name + " has ended");
    }

    public boolean setUpConnection(){
        try {
            //making a socket for sending
            System.out.println("Node " + name + " is setting up connection");
            node_send = new Socket("hostname", send);
            output = new PrintWriter(node_send.getOutputStream(),true);
            } catch (UnknownHostException e) {
            System.out.println("Error setting up socket connection: " + name + " :" + send);
            return false;
            } catch (IOException e) {
            System.out.println("Error setting up socket connection: " + name + " " + e);
            return false;
            }
        //telling the thread it is a sending thread
        Sending=true;
        System.out.println("Node " + name + " is ready for sending");
        return true;
    }

    public boolean setUpListen(){
    try{
        //making socket for Listening
        System.out.println("Node " + name + " is setting up listen");
        nodeListen = new ServerSocket(listen);
        System.out.println("Node " + name + " is trying to listen");
        node_rev = node_listen.accept();
        System.out.println("Node " + name + " NEVER GETS HERE");
        input = new BufferedReader(new InputStreamReader(node_rev.getInputStream()));
            } catch (UnknownHostException e) {
                System.out.println("Error setting up socket connection: " + name + " :" + listen);
                return false;
            } catch (IOException e) {
                System.out.println("Error setting up socket connection: " + name + " " + e);
                return false;
        }
        //telling the thread it is a Listening thread
        System.out.println("Node " + name + " is ready for listening");
        return true;
    }

    public void Listen(){
        try{
            line = input.readLine();
            //As long as something was sent and it was not terminate prints data
            if(line.equals("terminate")==false&&line.equals("null")==false)
            {
                System.out.println("Node " + name + " received:" + line);
            }
            //When terminate was sent it no longer looks for data 
            if(line.equals("terminate"))
            {
                Listening=false;
                node_listen.close();
                node_rev.close();
                input.close();
                System.out.println("Node " + name + " done listening");
            }
        }catch (IOException e) {
                System.out.println("Error Listening on connection: " + name + " " + e);
        }
    }

    public void Send(){
        try{
        //reads in the data and sends it to node
        line=reader.readLine();
        System.out.println(line);
        output.println(line);
        //if the data sent was terminate then exit sending mode
        if(line.equals("terminate")==true)
            {
                Sending=false;
                node_send.close();
                output.close();
                System.out.println("Node " + name + " done sending");
            }
        }catch (IOException e) {
                System.out.println("Error Sending on connection: " + name + " " + e);
        }
    }

    public int Checker(int temp) throws InterruptedException{
        boolean connected=setUpConnection();
            if(connected==true)
            {
                    //connected
                    temp=5;
            }
            return temp;
        }
}

每个conf文件都是这样设置的

confA.txt

5002
This is a sample line of text for node A.
This is another sample line of text for node A.
Node B will be printing out these three lines for node A.
terminate

confB.txt

5002
5005
This is a sample line of text.
This is another sample line of text.
Node C will be printing out these three lines.
terminate

confC.txt

5005

这就是我得到的输出

run:
Node A is starting
Node A is setting up connection
Node B is starting
Node B is setting up listen
Node C is starting
Node C is setting up listen
Node B is trying to listen
Node C is trying to listen
Error setting up socket connection: A java.net.ConnectException: Operation timed out
Node A is setting up connection
Error setting up socket connection: A java.net.ConnectException: Operation timed out
Node A is setting up connection
Error setting up socket connection: A java.net.ConnectException: Operation timed out
Node A is setting up connection
Error setting up socket connection: A java.net.ConnectException: Operation timed out
Node A is setting up connection
Error setting up socket connection: A java.net.ConnectException: Operation timed out
Node A has ended

代码似乎永远不会到达System.out.println行(“Node”+ name +“NEVER GETS HERE”);在setUpListen();

由于

3 个答案:

答案 0 :(得分:2)

这是因为ServerSocket.accept()阻塞,直到报告传入连接。该方法返回Socket

所以下一行(System.out.println("Node " + name + " NEVER GETS HERE"))永远不会执行,直到你有另一个网络接口连接到你的监听ServerSocket

我不确切地知道你想要实现的是什么,但是你需要在一个单独的线程中监听传入的连接:

final ServerSocket serverSocket = createServerSocket();
new Thread(new Runnable() {

    @Override
    public void run() {
        Socket socket = serverSocket.accept();
        System.out.println("Incoming connection from " + socket.getInetAddress());
        doSomethingWithSocket(socket);
    }
}).start();

PS:请坚持使用Java Naming Conventions

  • 类应始终以大写字母开头;
  • 字段名称(或类属性)应始终以小写字母开头;
  • 方法名称应始终以小写字母开头。

答案 1 :(得分:0)

事实证明我的问题是node_send = new Socket(" hostname",send);应该是node_send = new Socket(" localhost",send);

我很蠢。

但是我要感谢大家的帮助和指示。

答案 2 :(得分:-1)

公共类线程?会议请。

O.t:

Error setting up socket connection: C java.net.BindException: Address already in use

设置每个侦听器的端口是相同的。 (即地址已在使用中。)