gpt4 book ai didi

java - 如何创建仅在本地主机上服务的 Java Socket 对象?

转载 作者:行者123 更新时间:2023-11-30 04:01:28 24 4
gpt4 key购买 nike

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

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

有时候我的Client端可以连接到Server端,但通常我要等很长时间她才出来。我想,它应该与一些代理/防火墙有关。

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

最佳答案

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

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

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

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

祝你好运!

关于java - 如何创建仅在本地主机上服务的 Java Socket 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21905679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com