Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建仅在本地主机上服务的Java套接字对象?_Java_Sockets_Serversocket - Fatal编程技术网

如何创建仅在本地主机上服务的Java套接字对象?

如何创建仅在本地主机上服务的Java套接字对象?,java,sockets,serversocket,Java,Sockets,Serversocket,我在这里再次问这个问题(),因为前面提到的所有方法(简单地说,通过3个参数方法创建一个ServerSocket)都不能解决我的问题 我在一个大的内部网工作,每次打开一个浏览器时,我都需要输入我的代理帐户和密码才能访问互联网。这就是为什么我希望在本地主机上测试我的套接字程序 有时我的客户端可以连接服务器端,但通常我要等很长时间才能出来。我想,它应该与一些代理/防火墙相关 虽然我查看了以下所有资源,并相信它们都很值得一读,但我仍然无法解决我的问题 我的服务器端代码 import java.ne

我在这里再次问这个问题(),因为前面提到的所有方法(简单地说,通过3个参数方法创建一个ServerSocket)都不能解决我的问题

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

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

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

我的服务器端代码

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.");
    }
}
我试着用telnet,但根本连不上


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

  • 创建一个客户端(我原以为这一步会失败)
  • 尝试发送一些消息(但没有启动
    ServerSocket
  • 服务器已创建
  • 服务器将永远等待,阻止
    accept()上的主线程
  • 作为启动程序,使代码正常工作。创建两个测试类
    TestServer
    TestClient
    ,这两个类都必须具有
    main()
    方法。首先在自己的Java进程中启动
    TestServer
    。接下来在单独的Java进程中启动
    TestClient
    。这应该管用

    在一切正常工作之后,应该在服务器中引入一些并发性。按照目前的编写方式,一次只能为一个客户机提供服务。创建新线程以管理从
    accept()
    返回的新套接字


    祝你好运

    @JohnYin我很乐意!
    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();
        }
    
    }