简体   繁体   English

客户端和服务器使用Java中的套接字在单个文件中

[英]Client and Server in single file using socket in java

Can anyone please tell me how to create a server and client (both) in a single file? 谁能告诉我如何在一个文件中创建服务器和客户端(两者)?

I searched the net and came to know that it is possible using the threads. 我搜索了网络,发现可以使用线程。 I am not familiar with threads. 我对线程不熟悉。 I am trying to implement a peer to peer application. 我正在尝试实现对等应用程序。 At some point, the peer has to behave as server and client. 在某些时候,对等方必须充当服务器和客户端。 Can anyone please give a sample code or direct me to a good source? 任何人都可以提供示例代码或将我引导到一个好的来源吗?

Put simply, threads are parallel workflows that execute your code. 简而言之,线程是执行代码的并行工作流。 So if you have two instances of threads, you can have one of them execute method A, and one of them execute method B, and both will occur concurrently. 因此,如果您有两个线程实例,则可以让它们之一执行方法A,而其中一个执行方法B,并且两者都将同时发生。 The art and science of writing concurrent code is very advanced and takes a long while to master. 编写并发代码的技巧和科学非常先进,需要很长时间才能掌握。

However it's very easy to begin. 但是,开始非常容易。 For each piece of code you want to run separately, you create a class extending Thread, and put the code to be run in the overridden run() method. 对于要单独运行的每段代码,创建一个扩展Thread的类,然后将要运行的代码放在重写的run()方法中。 In your case, that could be a class Client extends Thread and class Server extends Thread . 在您的情况下,可能是class Client extends Thread class Server extends Thread class Client extends Thread class Server extends Thread Then, from the code initiating the threads (maybe your public static void main() method?) you instantiate both classes, and execute their start() method. 然后,从启动线程的代码(也许是您的public static void main()方法?)实例化两个类,并执行它们的start()方法。 Note that start() returns immediately; 请注意,start()立即返回; the code in run() then executes in concurrency. 然后, run()的代码并发执行。 So 所以

a.start();
b.start();

would actually return immediately and then both a and b are running in parallel. 实际上会立即返回,然后a和b并行运行。

Read this post . 阅读这篇文章 This post uses a Java UDP Server and Client code which connects with a Python UDP Client and Server code. 这篇文章使用了Java UDP服务器和客户端代码,并与Python UDP客户端和服务器代码连接。

You can make use of Java UDP Server and Client code. 您可以使用Java UDP Server和客户端代码。

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

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