简体   繁体   English

Java TCP 客户端/服务器

[英]Java TCP Client/Server

I have a problem which I do not know how to proceed further in Java TCP socket issue.我有一个问题,我不知道如何在 Java TCP 套接字问题中进一步处理。 So far as what we can get from the Internet, it's not hard to get quite a number of working solution for TCP server & client communication in Java.就我们可以从 Internet 上获得的内容而言,不难获得相当多的 Java 中 TCP 服务器和客户端通信的工作解决方案。 However, most of the example will have their server listen to a port, and then loop until they get a client which connects to the server, then the code will perform server.accept() and move further.但是,大多数示例将让他们的服务器侦听端口,然后循环直到他们获得连接到服务器的客户端,然后代码将执行 server.accept() 并进一步移动。 For example:例如:

 public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(PORT);
    System.out.println("Started: " + s);
    try {
      // Blocks until a connection occurs:
      Socket socket = s.accept();
      try {
        System.out.println("Connection accepted: "+ socket);

It will work perfectly if there's a client connecting to the server.如果有客户端连接到服务器,它将完美运行。 And, my problem is that I need to continue some other procedures even though there's no client connecting to the server.而且,我的问题是即使没有客户端连接到服务器,我也需要继续一些其他过程。 In fact, I will need to launch another JFrame to continue the procedures even if there is no client connecting to the same port and ip.事实上,即使没有客户端连接到相同的端口和 IP,我也需要启动另一个 JFrame 来继续该程序。 However, I have been struggling but as long as there is not client connecting to the server, my Java program will hang there with white popped up JFrame.但是,我一直在苦苦挣扎,但只要没有客户端连接到服务器,我的 Java 程序就会挂在那里,并弹出白色的 JFrame。

I would need to know how to overcome this as I am not quite sure whether there's a mistake in my understanding.我需要知道如何克服这个问题,因为我不太确定我的理解是否有错误。 Please assist and advice.请协助和建议。 Thank you!谢谢!

Best Regards, Yi Ying最好的问候, Yi Ying

Sounds like you need to do work in one thread whilst waiting for network connections on another.听起来您需要在一个线程中工作,同时等待另一个线程上的网络连接。 Check out the threading tutorial .查看 线程教程 Note that since you're using Swing, you have to be careful wrt.请注意,由于您使用的是 Swing,因此您必须小心。 which thread will modify your JFrame etc. and you should be aware of the SwingWorker utility.哪个线程将修改您的 JFrame 等,您应该了解SwingWorker实用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM