gpt4 book ai didi

java - 服务器与客户端通信问题

转载 作者:行者123 更新时间:2023-12-01 15:52:14 25 4
gpt4 key购买 nike

我正在使用 Java 上的客户端-服务器程序示例。我遇到了这样的问题:我使用 8080 端口和本地主机启动服务器,然后启动客户端并发出请求。请求完成后,两个程序都会关闭套接字,因此我无法重复我的操作。如何使用同一个客户端和同一个服务器发出多个请求?

    public class Network extends Thread
{
MasterEdit ME = new MasterEdit();
private Socket _socket;
InputStream is; //Data streams
OutputStream os;
/**
* Network class constructor
*/
public Network(int port, int backlog, InetAddress address)
{
//We create an object of SocketFactory
SocketFactory sf = new SocketFactory();
//Save server socket
ServerSocket ss = null;

try
{
if(address == null) //If there is no host
{
if(backlog <= 0) //If backlog is not given we create it with port
{ ss = sf.createServerSocket(port);
System.out.println("Success");
}
else
ss = sf.createServerSocket(port, backlog); //If backlog is given we just create it
}
else
ss = sf.createServerSocket(port, backlog, address); //If everything is given we create it using data
}
catch(Exception e)
{
//Exception with creation of socket
System.err.println("Failed open server socket");
System.exit(1); //Stop program and send 1 as a exception-code
}

while(true) //Listening to the socket
{
try
{
StartThread(ss.accept()); //If client has connected we send him to the daemon
}
catch (IOException e)
{
e.printStackTrace();
}
}

}

/**
* Start daemon-tool when client has connected
*/
private void StartThread(Socket ss)
{
_socket = ss; //initializing of global variable

setDaemon(true); //anounce that new potok is daemon
setPriority(NORM_PRIORITY); //set the priority
start(); //Start it
}

@Override
public void run()
{
byte buffer[] = new byte[64*1024]; //buffer in 64 kb
try
{
is = _socket.getInputStream();
os = _socket.getOutputStream(); //Initializing the output stream to a client
String toClient = SearchRequest(new String(buffer, 0, is.read(buffer)));
os.write(toClient.getBytes()); //Sending an answer
}
catch(Exception e)
{
e.printStackTrace();
}

}

private String SearchRequest(String request)
{
String info = ""; //Initializing of a variable

if(request.equalsIgnoreCase("info")) //Check the request
{
//Adding data
info += "Virtual Machine Information (JVM)n";
info += "JVM Name: " + System.getProperty("java.vm.name")+"n";
info += "JVM installation directory: " + System.getProperty("java.home")+"n";
info += "JVM version: " + System.getProperty("java.vm.version")+"n";
info += "JVM Vendor: " + System.getProperty("java.vm.vendor")+"n";
info += "JVM Info: " + System.getProperty("java.vm.info")+"n";
return info; //Give the answer
}
if(request.charAt(0)=='0') {
StringTokenizer rm = new StringTokenizer(request, " \t\n\r,:");
rm.nextToken();
ME.MasterDell(Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()));
return "Successfully deleted";
}
if(request.charAt(0)=='1'){
StringTokenizer temp = new StringTokenizer(request, " \t\n\r,:");
temp.nextToken();
ME.MasterAdd(Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), temp.nextToken());
return "Successfully added";
}
this.ClostIt();
return "Bad request"; //bad request
}
public void ClostIt() {
try {
is.close();
os.close();
_socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

这是服务器部分。它使用 SocketFactory 类,但主要只是在开始时创建一个套接字。在主程序中,我调用 new Network(PORT, BACKLOG, InetAddress.getByName(host));

最佳答案

我猜你的服务器程序中没有循环,而是类似这样的东西:

public static void main( String args[] ) {
ServerSocket server = new ServerSocket(...);
Socket con = server.accept();
//process the client connection ...
//done, exit!
}

而不是

public static void main( String args[] ) {
ServerSocket server = new ServerSocket(...);
Socket con = null;
while( condition /* e.g. shutdown server message received */ ) {
con = server.accept();
//process the client connection ...
//then keep waiting for the next request
}
//done, exit!
}

请记住,上述示例一次仅处理一个客户端!您将需要进入多线程来处理并发客户端。

关于java - 服务器与客户端通信问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5792610/

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