客户端和服务器使用Java中的套接字在单个文件中 [英] Client and Server in single file using socket in java

查看:72
本文介绍了客户端和服务器使用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?

推荐答案

简单地说,线程是执行代码的并行工作流.因此,如果您有两个线程实例,则可以让它们之一执行方法A,而其中一个执行方法B,并且两者都将同时发生.编写并发代码的技巧和科学非常先进,需要很长时间才能掌握.

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. The art and science of writing concurrent code is very advanced and takes a long while to master.

但是,开始非常容易.对于要单独运行的每段代码,创建一个扩展Thread的类,然后将要运行的代码放在重写的run()方法中.在您的情况下,可能是class Client extends Threadclass Server extends Thread.然后,从启动线程的代码(也许是public static void main()方法?)实例化这两个类,并执行它们的start()方法.请注意,start()立即返回;然后run()中的代码并发执行.所以

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. In your case, that could be a class Client extends Thread and 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. Note that start() returns immediately; the code in run() then executes in concurrency. So

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

实际上会立即返回,然后a和b都并行运行.

would actually return immediately and then both a and b are running in parallel.

这篇关于客户端和服务器使用Java中的套接字在单个文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆