如何仅在localhost上创建Java Socket对象?

时间:2014-02-20 10:59:21

标签: java sockets serversocket

我在这里再次提出这个问题(How to create Java socket that is localhost only?)'因为前面提到的所有方法(简单地说是用3参数方法创建一个ServerSocket)都无法解决我的问题。

我在一个大型内部网中工作,每当我打开一个浏览器时,我需要输入我的代理帐户和密码才能访问互联网。这就是为什么我希望在localhost上测试我的套接字程序。

偶尔我的客户端可以连接服务器端,但通常我必须等待很长时间才能出来。我想,它应该与一些代理/防火墙有关。

enter image description here

虽然我查看了以下所有资源,并相信所有资源都值得一读,但我仍然无法解决问题。

http://zerioh.tripod.com/ressources/sockets.html

How to determine an incoming connection is from local machine

我的服务器端代码

import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.net.InetAddress;

public class Myserver {
    private int serverPort = 8000;
    private ServerSocket serverSock = null;

    public Myserver(int serverPort) {
        this.serverPort = serverPort;

        try {
            /*SocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName("localhost"), serverPort);
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.bind(socketAddress);
            serverSocket.accept();*/
            serverSock = new ServerSocket(serverPort, 0, InetAddress.getByName(null));

        }
        catch (IOException e){
            e.printStackTrace(System.err);
        }
    }
     public void handleConnection(InputStream sockInput, OutputStream sockOutput) {
        while(true) {
            byte[] buf=new byte[1024];
            int bytes_read = 0;
            try {
                // This call to read() will wait forever, until the
                // program on the other side either sends some data,
                // or closes the socket.
                bytes_read = sockInput.read(buf, 0, buf.length);

                // If the socket is closed, sockInput.read() will return -1.
                if(bytes_read < 0) {
                    System.err.println("Tried to read from socket, read() returned < 0,  Closing socket.");
                    return;
                }
                System.err.println("Received "+bytes_read
                                   +" bytes, sending them back to client, data="
                                   +(new String(buf, 0, bytes_read)));
                sockOutput.write(buf, 0, bytes_read);
                // This call to flush() is optional - we're saying go
                // ahead and send the data now instead of buffering
                // it.
                sockOutput.flush();
               // sockOutput.close();

            }
            catch (Exception e){
                System.err.println("Exception reading from/writing to socket, e="+e);
                e.printStackTrace(System.err);
                return;
            }

        }

    }

    public void waitForConnections() {
        Socket sock = null;
        InputStream sockInput = null;
        OutputStream sockOutput = null;
        while (true) {
            try {
                // This method call, accept(), blocks and waits
                // (forever if necessary) until some other program
                // opens a socket connection to our server.  When some
                // other program opens a connection to our server,
                // accept() creates a new socket to represent that
                // connection and returns.
                sock = serverSock.accept();
                System.err.println("Have accepted new socket.");

                // From this point on, no new socket connections can
                // be made to our server until we call accept() again.

                sockInput = sock.getInputStream();
                sockOutput = sock.getOutputStream();
            }
            catch (IOException e){
                e.printStackTrace(System.err);
            }

            // Do something with the socket - read bytes from the
            // socket and write them back to the socket until the
            // other side closes the connection.
            handleConnection(sockInput, sockOutput);

            // Now we close the socket.
            try {
                System.err.println("Closing socket.");
                sock.close();
            }
            catch (Exception e){
                System.err.println("Exception while closing socket.");
                e.printStackTrace(System.err);
            }

            System.err.println("Finished with socket, waiting for next connection.");
        }
    }

}

我的客户端代码

import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

public class MyClient {
    private String serverHostname = null;
    private int serverPort =0;
    private byte[] data = null;
    private Socket sock = null;
    private InputStream sockInput = null;
    private OutputStream sockOutput = null;

    public MyClient(String serverHostname, int serverPort, byte[] data){
        this.serverHostname =  serverHostname;
        this.serverPort = serverPort;
        this.data = data;
    }

    public void sendSomeMessages(int iterations) {
        System.err.println("Opening connection to "+serverHostname+" port "+serverPort);
        try {
            sock = new Socket(serverHostname, serverPort);
            sockInput = sock.getInputStream();
            sockOutput = sock.getOutputStream();
        }
        catch (IOException e){
            e.printStackTrace(System.err);
            return;
        }

        System.err.println("About to start reading/writing to/from socket.");

        byte[] buf = new byte[data.length];
        int bytes_read = 0;
        for(int loopi = 1; loopi <= iterations; loopi++) {
            try {
                sockOutput.write(data, 0, data.length); 
                bytes_read = sockInput.read(buf, 0, buf.length);
            }
            catch (IOException e){
                e.printStackTrace(System.err);
            }
            if(bytes_read < data.length) {
                System.err.println("run: Sent "+data.length+" bytes, server should have sent them back, read "+bytes_read+" bytes, not the same number of bytes.");
            }
            else {
                System.err.println("Sent "+bytes_read+" bytes to server and received them back again, msg = "+(new String(data)));
            }

            // Sleep for a bit so the action doesn't happen to fast - this is purely for reasons of demonstration, and not required technically.
            try { Thread.sleep(50);} catch (Exception e) {}; 
        }
        System.err.println("Done reading/writing to/from socket, closing socket.");

        try {
            sock.close();
        }
        catch (IOException e){
            System.err.println("Exception closing socket.");
            e.printStackTrace(System.err);
        }
        System.err.println("Exiting.");
    }
}

我的测试代码

import java.net.*;

public class Mytest {


    public static void main(String[] args) {
    String hostname = "localhost";
        int port = 8000;

        try {
            InetAddress add = InetAddress.getLocalHost();

             System.out.println( add);
        }
        catch (UnknownHostException e)
                {
                     e.printStackTrace(); 
                }


        byte[] data = "my program".getBytes();

        MyClient client = new MyClient(hostname, port, data);
        client.sendSomeMessages(10);   

       Myserver server = new Myserver(port);
        server.waitForConnections();
    }

}

我尝试使用telnet,但我根本无法连接它

enter image description here

1 个答案:

答案 0 :(得分:2)

第一个问题是测试代码运行 客户端和服务器。在Mytest.main()中,主线程执行以下操作:

  1. 创建一个客户端(我原以为这一步会失败)
  2. 尝试发送一些消息(但没有启动ServerSocket
  3. 创建服务器
  4. 服务器永远等待,阻止accept()
  5. 上的主线程

    作为让您的代码正常工作的入门者。创建两个测试类TestServerTestClient,这两个测试类必须具有main()方法。首先在它自己的Java进程中启动TestServer。接下来在单独的Java进程中启动TestClient。这个工作!

    在您完成所有工作之后,您应该在服务器中引入一些并发性。它当前编写的方式一次只能为一个客户端提供服务。创建新线程以管理从accept()返回的新套接字。

    祝你好运!