HTML   发布时间:2022-04-15  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何将在命令提示符上运行的客户端 – 服务器聊天应用程序转换为基于Web的应用程序?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用套接字编程创建了多个客户端 – 服务器聊天应用程序,我可以在命令提示符下将其部署为JAR文件.现在我需要做些什么来改变使用tomcat服务器在Web浏览器上运行这个应用程序?

我的服务器代码:

package com.Aricent;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
import java.sql.DriveRMANager;

public class Server {

    static ServerSocket serverSocket=null;
    static Socket clientSocket=null;
    static final int max=20;
    static clientThread[] threads=new clientThread[max];
    public static void main(String arg[])
    {
        int portnumber=2222;
        try{
        serverSocket=new ServerSocket(portnumber);
        }catch(IOException E)
        {
            System.out.println(E);
        }

        while(true)
        {
            try{
                clientSocket=serverSocket.accept();
                int i=0;
                for(i=0;i<max;i++)
                {
                    if(threads[i]==null)// searching for empty position
                    {
                        (threads[i]=new clientThread(clientSocket,threads)).start();
                        break;
                    }
                }
                if(i==maX)
                {
                    PrintStream os=new PrintStream(clientSocket.getOutputStream());
                    os.println("Server too busy. Try later");
                    os.close();
                    clientSocket.close();
                }
            }catch(IOException E)
            {
                System.out.println(E);
            }
        }
    }

}


class clientThread extends Thread
{
    String clientName=null;
    DataInputStream is=null;
    PrintStream os=null;
    Socket clientSocket=null;
    clientThread[] threads;
    int max;
    String dbPath="jdbc:mysql://172.19.24.66:3306/chatdb";
    String dbUser="root";
    String dbPass="root";

    public clientThread(Socket clientSocket,clientThread[] threads)
    {
        this.CLIENtSocket=clientSocket;
        this.threads=threads;
        max=threads.length;
    }

    public void run()
    {

        int max=this.max;
        clientThread[] threads=this.threads;
        Boolean choice=false;
        String sender="";



        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriveRMANager.getConnection(dbPath,dbUser,dbPass);
            PreparedStatement ps=null;
            ResultSet rs=null;
            Statement stmt=con.createStatement();
            String query="";


            is=new DataInputStream(clientSocket.geTinputStream());
            os=new PrintStream(clientSocket.getOutputStream());
            String name="";
            String ch="";
            Boolean login=false;
            while(!login)
            {
                os.println("*** Press 1 to login or press 2 to register***");
                ch=is.readLine();
                os.println(ch);
                if(ch.equals("1"))
                {
                    os.println("Enter your username and password...");
                    String uname=is.readLine();
                    String upass=is.readLine();
                    query="SELEct * from user where username= '"+uname+"' and password= '"+upass+"'";
                    rs=stmt.executeQuery(query);
                    if(rs.next() && !rs.getString("status").equals("online"))
                    {
                        query="update user set status='online' where username='"+uname+"'";
                        stmt.executeupdate(query);
                        login=true;
                        name=uname;
                    }
                    else
                        os.println("Sorry wrong credentials");
                }
                else if(ch.equals("2"))
                {
                    os.println("Enter your username and password and emailId for registration...");
                    String uname=is.readLine();
                    String upass=is.readLine();
                    String uemail=is.readLine();
                    query="SELEct username from user where emailId= '"+uemail+"'";
                    rs=stmt.executeQuery(query);
                    if(rs.next() )
                    {
                        os.println("Sorry user- "+rs.getString("username")+" already registered with this mail id");

                    }
                    else
                    {
                        query="insert into user (username,password,emailId,status) value('"+uname+"','"+upass+"','"+uemail+"','offline')";
                        stmt.executeupdate(query);
                        os.println("Registration successful...");
                    }
                }
                else
                    os.println("Wrong input");
            }






            os.println("Welcome "+ name+" to chat room. \n To leave enter: /stop \n To start private chat enter: /Private USERNAME YOUR messaGE \n To stop private chat enter: /endPrivate");
            synchronized(this){
                for(int i=0;i<max;i++)
                {
                    if(threads[i]!=null && threads[i]==this){
                        clientName=name;
                        break;
                    }
                }

                for(int i=0;i<max;i++)
                {
                    if(threads[i]!=null&& threads[i]!=this)
                    {
                        threads[i].os.println("*NEW USER "+name+" ENTERed CHAT ROOM*");

                    }
                }
            }

            while(true)
            {
                int pos=0;
                String line=is.readLine();
                if(line.startsWith("/stop"))
                {
                    break;
                }
                if(line.startsWith("/endPrivate"))
                {
                    choice=false;

                }
                if(line.startsWith("/Private") || choice==true )
                {
                    choice=true;
                    //String words[];
                    if(line.startsWith("/Private"))
                    {
                        //pos=2;
                         String words[]=line.split("\\s",3);
                         sender=words[1];
                        synchronized(this)
                        {
                            for(int i=0;i<max;i++)
                            {
                                if(threads[i]!=null && threads[i]!=this && threads[i].clientName.equals(words[1]) )
                                {
                                    threads[i].os.println("<"+name+">"+words[2]);
                                    this.os.println(">>"+name+" "+words[2]); //showing the sender that msg is sent
                                    break;
                                }
                            }
                        }

                    }
                    else
                    {
                    String words[]=line.split("\\s",1);
                    synchronized(this)
                    {
                        for(int i=0;i<max;i++)
                        {
                            if(threads[i]!=null && threads[i]!=this && threads[i].clientName.equals(sender) )
                            {
                                threads[i].os.println("<"+name+">"+words[0]);
                                this.os.println(">>"+name+" "+words[0]); //showing the sender that msg is sent
                                break;
                            }
                        }
                    }
                    }
                    }
                else
                {
                    synchronized(this){
                        for(int i=0;i<max;i++)
                        {
                            if(threads[i]!=null  && threads[i].clientName!=null )
                            {
                                threads[i].os.println("< "+name+" > "+linE);
                                //threads[i].os.println("** The user "+name+" is leaving the chat room **");
                            }
                        }

                    }
                }
            }

            //after while
            synchronized(this)
            {
                for(int i=0;i<max;i++)
                {
                    if(threads[i]!=null  && threads[i].clientName!=null )
                    {

                        threads[i].os.println("** The user "+name+" is leaving the chat room **");
                    }
                }
            }
                    os.println("** Bye "+name+" **");

                    synchronized(this)
                    {
                        for(int i=0;i<max;i++)
                        {
                            if(threads[i]==this)
                            {
                                threads[i]=null;
                            }




                }


            }
                    is.close();
                    os.close();
                    clientSocket.close();





        }catch(Exception E)
        {
            System.out.println(E);
        }




    }

}

客户代码:

package com.Aricent;

import java.io.*;
import java.net.*;

public class Client implements Runnable {

    static Socket clientSocket=null;
    static PrintStream os=null;
    static DataInputStream is=null;
    static BufferedReader inputLine=null;
    static Boolean closed=false;

    public static void main(String arg[])
    {
        int portnumber=2222;
        String host="localhost";

        try{
            clientSocket=new Socket(host,portnumber);
            inputLine=new BufferedReader(new InputStreamReader(System.in));
            os=new PrintStream(clientSocket.getOutputStream());
            is=new DataInputStream(clientSocket.geTinputStream());

        }
        catch(Exception E)
        {
            System.out.println(E);
        }

        if(clientSocket!=null&&os!=null&&is!=null)
        {
            try{
                new Thread(new Client()).start();
                while(!closed)
                {
                    os.println(inputLine.readLine().trim());
                }
                os.close();
                is.close();
                clientSocket.close();
            }catch(IOException E)
            {
                System.out.println(E);
            }
        }

    }





    //@Override
    public void run() {
        // TODO Auto-generated method stub

        String responseLine;
        try{
            while((responseLine=is.readLine())!=null)
            {
                System.out.println(responseLinE);
                if(responseLine.indexOf("*** Bye")!=-1)
                    break;
            }
            closed=true;
        } catch(Exception E)
        {
            System.out.println(E);
        }

    }


}

我的主要问题是如何在本tomcat服务器中引入套接字编程?

解决方法

我几年前发布了完整的解决方案,但它使用Nodejs作为服务器. Building a chat app that uses a node.js server in IOS.此应用程序使用服务器推送技术(Web套接字).

如果您希望将当前代码迁移到浏览器中,那么只需调整服务器线程以使用浏览器中的http,您就可以进行几周的工作.浏览器通过http协议与服务器通信,该协议比当前解决方案高一层.您的解决方案是使用普通网络套接字.

但是,您可以在tomcat和普通Web应用程序上使用servlet构建一个长轮询类型的应用程序,该应用程序会反复检查服务器是否有新的聊天消息(每隔几秒钟发出一次新请求),或者尝试使用最新的tomcat Websocket支持. tomcat的示例中有示例聊天应用程序.下载zip,请参阅/apache-tomcat-8.0.35/webapps/examples/websocket/.

大佬总结

以上是大佬教程为你收集整理的如何将在命令提示符上运行的客户端 – 服务器聊天应用程序转换为基于Web的应用程序?全部内容,希望文章能够帮你解决如何将在命令提示符上运行的客户端 – 服务器聊天应用程序转换为基于Web的应用程序?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。