如何在lan上与客户端建立连接

时间:2012-12-08 17:38:38

标签: java

我创建了一个有效的服务器和客户端应用程序。但客户端或服务器无法正常工作。如果你运行服务器并在同一台机器上运行客户端它工作。但是如果你在一台机器上运行服务器并在另一台机器上运行客户端它就不起作用。如果你能帮助我找出为什么它不允许连接或如何在两台计算机之间建立连接将是伟大的。谢谢你的负担。代码如下:

server-----------------------------------------------------------------

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

import javax.swing.*;

public class AdditionalServer extends JFrame {
    private JTextArea textWindow= new JTextArea();
    private int port;

    // the constructor
    public AdditionalServer(int portIn)
    {
        port = portIn;
        setTitle("Addition Sever");
        add("Center",textWindow);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,300);
        setVisible(true);
        startServer();
    }

    private void startServer() {
        // TODO Auto-generated method stub
        // declare a "general" socket and a server socket
        Socket connection;
        ServerSocket listenSocket;
        //declare low level and high level objects for input
        InputStream inStream;
        DataInputStream inDataStream;

        // declare low level and high level objects for output
        OutputStream outStream;
        DataOutputStream outDataStream;

        // declare other variables
        String client;

        boolean connected;

        while(true){
            try{
                // create a server socket
                listenSocket= new ServerSocket(port,0, InetAddress.getLocalHost());
            //  listenSocket= new ServerSocket(port);
                textWindow.append("Listening on port "+ port +"\n");

                //listen for a connection from the client 
                connection =listenSocket.accept();
                connected = true;

                // create an input stream from the client
                inStream = connection.getInputStream();
                inDataStream = new DataInputStream(inStream);

                // create an output stream from the client
                outStream = connection.getOutputStream();
                outDataStream = new DataOutputStream(outStream);

                // wait for a string from the client
                client = inDataStream.readUTF();
                textWindow.append("Connection esablished with "+ client+ "\n");

                int first, second,sum1;
                String sum = "hi";
                while(connected){
                    //read an integer from the client
                    first = inDataStream.readInt();
                    textWindow.append("First number receievd: "+ first + "\n");

                    //read an integer from the client
                    second = inDataStream.readInt();
                    textWindow.append("Second number receievd: "+ second + "\n");

                    sum1 = first + second;
                    textWindow.append("Sum returned: " + sum1 +"\n");

                    // send the sum to the client 
                    outDataStream.writeInt(sum1);
                    //outDataStream.writeUTF("hi");
                }
            }catch(IOException e){
                connected = false;
            }
        }
    }

    public static void main (String args []){
        new AdditionalServer(8900);

    }
}

client----------------------------------------------------------------------
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class AdditionClient extends JFrame implements ActionListener {

    // declare the visual components

    private JTextField firstNumber = new JTextField(3);
    private JLabel plus = new JLabel("+");
    private JTextField secondNumber = new JTextField(3);
    private JLabel equals = new JLabel("=");
    private JLabel sum= new JLabel();
    private JTextField msg = new JTextField(20);
    private JButton addButton= new JButton("Press to see the sum of the two numbers");

    // declare low level and high level objects for input
    private InputStream inStream;
    private DataInputStream inDataStream;

    // declare low level and high level objects for output
    private OutputStream outStream;
    private DataOutputStream outDataStream;

    // declare socket
    private Socket connection;

    // declare attribute to told details of remote machine and port
    private String remoteMachine;
    private int port;

    // constructor

    public AdditionClient(String remoteMachineIn, int portIn){
        remoteMachine = remoteMachineIn;
        port= portIn;

        //add the visual components
        add(firstNumber);
        add(plus);
        add(secondNumber);
        add(equals);
        add(sum);
        add(msg);
        add(addButton);

        // configure the frame
        setLayout(new FlowLayout());
        setTitle("Addtion Client");
        msg.setHorizontalAlignment(JLabel.CENTER);
        addButton.addActionListener(this);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,150);
        setVisible(true);

        //start the helper method that starts the client
        startClient();
    }

    private void startClient() {
        // TODO Auto-generated method stub
        try{
            // attempt to create a connection to the server
            connection = new Socket(remoteMachine,port);
            msg.setText("connection establish");

            // create an input stream from the server
            inStream = connection.getInputStream();
            inDataStream = new DataInputStream(inStream);

            //create output stream to the server
            outStream = connection.getOutputStream();
            outDataStream = new DataOutputStream(outStream);

            //send the host IP to the server
            outDataStream.writeUTF(connection.getLocalAddress().getHostAddress());

        }catch (UnknownHostException e){
            msg.setText("Unknow host");
        }
        catch (IOException except){
            msg.setText("Network Exception");
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        try{
            // send the two integers to the server
            outDataStream.writeInt(Integer.parseInt(firstNumber.getText()));
            outDataStream.writeInt(Integer.parseInt(secondNumber.getText()));

            //read and display the results sent back from the server
            //String results= inDataStream.readUTF();
            int results= inDataStream.readInt();
            sum.setText(""+results);
        }catch(IOException ie){
            ie.printStackTrace();
        }
    }

    public static void main (String args[]){
        new AdditionClient("192.168.07", 8900);
    }
}

1 个答案:

答案 0 :(得分:2)

我认为你的问题就在这里。

listenSocket= new ServerSocket(port,0, InetAddress.getLocalHost());

InetAddress.getLocalHost()应该是你的绑定ip。在这里提供您的机器IP,并且您的客户也应该可以看到它。我建议您从客户端计算机发送ping请求。

尝试执行ping "your bind ip"检查您的服务器计算机是否可以通过网络访问。

或尝试仅提供端口。

listenSocket= new ServerSocket(port)