Java多线程聊天应用|

Java 多线程聊天应用程序 |第二集(客户端编程)

原文:.geesforgeks.org/multithreading-chat-application-setting-2/

先决条件:Socket 编程中的线程介绍,多线程聊天应用程序 |设置 1

本文介绍了多线程聊天应用程序的客户端程序的实现。到目前为止,套接字编程中的所有示例都假设客户端首先发送一些信息,然后服务器或其他客户端用该信息进行响应。在现实世界中,情况可能并非如此。无需向某人发送消息即可接收消息。每当将消息传递给客户端时,客户端应该能够轻松地接收消息应用编程接口和套接字,即发送和接收必须作为单独的活动而不是顺序来实现。使用线程对此功能有一个特别简单的解决方案。在客户端实现中,我们将创建两个线程:

发送消息:该线程将用于向其他客户端发送消息。这项工作很简单,它需要输入要发送的消息和要发送到的发件人。请注意,此实现假定消息的格式为 message#sender,其中 sender 是发件人的姓名。之后,它将消息写入附加到客户端处理程序的输出流中。处理程序分解消息和接收器部分并将它们传递给特定的接收器。让我们看看如何实现这个线程。

“`javaThreadsendMessage=newThread(newRunnable(){@Overridepublicvoidrun(){while(true){

//readthemessagetodeliver.Stringmsg=sc.nextLine();try{

//writeontheoutputstreamdos.writeUTF(msg);}catch(IOExceptione){e.printStackTrace();}}}});“`

阅读消息:类似的技巧用于创建接收消息的线程。当任何客户端尝试写入客户端的输入流时,我们使用 readUTF() 来读取消息。下面显示了该线程如何实现的片段-

“`javaThreadreadMessage=newThread(newRunnable(){

@Overridepublicvoidrun(){

while(true){try{

//readthemessagesenttothisclientStringmsg=dis.readUTF();System.out.println(msg);}catch(IOExceptione){

e.printStackTrace();}}}});“`

客户端编程的其余步骤与上面的示例类似。简要说明如下——

构建插件连接通信 通信是在 readMessage 和 sendMessage 线程的帮助下完成的。单独的读写线程确保消息同时发送和接收。

// Java implementation for multithreaded chat client
// Save file as Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client 
{
    final static int ServerPort = 1234;
    public static void main(String args[]) throws UnknownHostException, IOException 
    {
        Scanner scn = new Scanner(System.in);
        // getting localhost ip
        InetAddress ip = InetAddress.getByName("localhost");
        // establish the connection
        Socket s = new Socket(ip, ServerPort);
        // obtaining input and out streams
        DataInputStream dis = new DataInputStream(s.getInputStream());
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        // sendMessage thread
        Thread sendMessage = new Thread(new Runnable() 
        {
            @Override
            public void run() {
                while (true) {
                    // read the message to deliver.
                    String msg = scn.nextLine();
                    try {
                        // write on the output stream
                        dos.writeUTF(msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        // readMessage thread
        Thread readMessage = new Thread(new Runnable() 
        {
            @Override
            public void run() {
                while (true) {
                    try {
                        // read the message sent to this client
                        String msg = dis.readUTF();
                        System.out.println(msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        sendMessage.start();
        readMessage.start();
    }
}

输出:来自客户端 0:

hello#client 1
client 1 : heya
how are you#client 1
client 1 : fine..how about you
logout

来自客户端 1:

client 0 : hello
heya#client 0
client 0 : how are you
fine..how about you#client 0
logout

关键点:

如何运行上述程序?

与上面的示例类似,先运行服务器,然后运行多个客户端实例。从每个客户端,尝试向另一个客户端发送消息。确保只向有效的客户端发送消息应用编程接口和套接字,即发送给活动列表中可用的客户端。

建议的改进

这只是解释如何使用线程和套接字编程来创建强大的程序的一部分。对于上面的实现,有一些建议给感兴趣的读者-

本文由 Rishab Mahesh 提供。如果您喜欢 GeeksforGeeks 并想投稿,您还可以使用contribute.geeksforgeeks.org 撰写文章或将您的文章发送至contribute@geeksforgeeks.org。听到您的文章出现在极客博客主页上并帮助其他极客。

如果您发现任何不准确之处,或者如果您想分享有关之前讨论过的主题的更多信息,请发表评论。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悟空资源网 网站程序 Java多线程聊天应用| http://www.wkzy.net/game/8241.html

常见问题

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务