网络聊天室 (linux,java,Android)

如果追忆会荡起涟漪,那么今天的秋红落叶和晴空万里都归你

前几天在他人那里看到了网络聊天室的文章,想起了自己几年前也认认真真写过相关编程,实现了服务端,客户端,客户端有c,java,Android三种方式实现

关注公众号「技术乱舞」,一起进步!

网络聊天室小项目,可以学习一下网络编程,实现的小功能有云端保存聊天记录,登录聊天室获取云端聊天记录,服务端采用c程序实现,客户端采用三种方式,C、java、Android三种方式实现,简易的实现了群聊的过程,同时也使用udp的方式实现了更简易的聊天室,话不多说,上代码。

服务端(C)

1#include .. 2 3#define MAXNUM 10 4#define IP "172.31.207.15" 5short PORT = 8000; 6int severSock; 7int clientSock[MAXNUM]; 8 9void SendMsg(char *msg) 10{ 11    int i; 12    char tempmsg[286]; 13    strcpy(tempmsg, msg); 14    char nowtime[10]; 15    char sendbuffer[500] = {}; //最终消息发送 16    time_t t; 17    struct tm *lt; 18    time(&t); 19    lt = localtime(&t); 20    sprintf(nowtime, "[%d:%d:%d]", lt->tm_hour, lt->tm_min, lt->tm_sec); 21 22    strcat(sendbuffer, nowtime); 23    strcat(sendbuffer, tempmsg); 24    for (i = 0; i < MAXNUM; ++i) 25    { 26        if (clientSock[i] != 0) 27        { 28            printf("发送至客户[ %d ]\n", clientSock[i]); 29            send(clientSock[i], sendbuffer, strlen(sendbuffer), 0); 30        } 31    } 32 33    FILE * wfile = fopen("./allmsg.txt","a+"); 34    fwrite(sendbuffer,strlen(sendbuffer),1,wfile); 35    fwrite("\n",strlen("\n"),1,wfile); 36    fclose(wfile); 37    printf("消息记录完毕\n"); 38    printf("===================\n"); 39} 40 41void *userthread(void *arg) 42{ 43    //char sendmsg[300]; 44    int usersock = *(int *)arg; 45    printf("客户 Socket[ %d ]:\n", usersock); 46    while (1) 47    { 48        char usermsg[286] = {}; 49        //memset(sendmsg, 0, sizeof(sendmsg)); 50        memset(usermsg, 0, sizeof(usermsg)); 51        if (recv(usersock, usermsg, sizeof(usermsg), 0) <= 0) 52        { 53            int i; 54            for (i = 0; i < MAXNUM; ++i) 55            { 56                if (usersock == clientSock[i]) 57                { 58                    clientSock[i] = 0; 59                    break; 60                } 61            } 62 63            printf("用户 %d 已退出!\n", usersock); 64            pthread_exit((void *)i); 65        } 66 67        if(strcmp(usermsg,"[online]")==0) 68        { 69            printf("%d客户端查询消息记录\n",usersock); 70            FILE * sendfile = fopen("./allmsg.txt","r"); 71            char allmsg[1024*10]={}; 72            char allmsgsend[1024*11] = {}; 73            fread(allmsg,sizeof(allmsg),1,sendfile); 74            strcat(allmsgsend,"\n--------漫游记录--------\n"); 75            strcat(allmsgsend,allmsg); 76            strcat(allmsgsend,"\n-------漫游记录查询完毕---\n"); 77            send(usersock,allmsgsend,strlen(allmsgsend),0); 78            fclose(sendfile); 79            printf("==================\n"); 80            continue; 81        } 82        SendMsg(usermsg); 83    } 84} 85 86int main() 87{ 88    severSock = socket(AF_INET, SOCK_STREAM, 0); 89    struct sockaddr_in severAddr; 90    memset(&severAddr, 0, sizeof(severAddr)); 91    severAddr.sin_family = AF_INET; 92    severAddr.sin_addr.s_addr = inet_addr(IP); 93    severAddr.sin_port = htons(PORT); 94 95    if (bind(severSock, (struct sockaddr *)&severAddr, sizeof(severAddr)) == -1) 96    { 97        perror("绑定失败!!!"); 98        exit(-1); 99    } 100    if (listen(severSock, MAXNUM) == -1) 101    { 102        perror("监听失败!!!"); 103        exit(-1); 104    } 105    printf("|****服务器启动成功****|\n"); 106    // struct sockaddr_in tempaddr; 107    // socklen_t len = sizeof(tempaddr); 108 109    while (1) 110    { 111        struct sockaddr_in tempaddr; 112        socklen_t len = sizeof(tempaddr); 113        //memset(&tempaddr, 0, sizeof(tempaddr)); 114        int sockid = accept(severSock, (struct sockaddr *)&tempaddr, &len); 115        if (sockid == -1) 116        { 117            printf("客户端连接失败!!!\n"); 118            continue; 119        } 120        int i = 0; 121        for (i = 0; i < MAXNUM; ++i) 122        { 123            if (clientSock[i] == 0) 124            { 125                clientSock[i] = sockid; 126                printf("新的客户端已连接,socket: %d\n", sockid); 127                pthread_t userthrd; 128                pthread_create(&userthrd, 0, userthread, &sockid); 129                break; 130            } 131 132            if (i == MAXNUM) 133            { 134                char *str = "不好意思,满员了。"; 135                send(sockid, str, strlen(str), 0); 136                close(sockid); 137            } 138        } 139    } 140}

客户端(java)

1import java.io.*; 2import java.net.*; 3import java.util.*; 4 5public class chatconnect { 6    private static String ipaddr = "47.104.86.151"; 7    static InputStream inStream; 8    public static String mess=" "; 9    public static String yname=null; 10    public static void main(String[] args) { 11        // TODO Auto-generated method stub 12        Socket s = null;     13        RecvThread rth=new RecvThread(); 14        try { 15            s =new Socket(ipaddr,8000); 16        } catch (UnknownHostException e1) { 17            // TODO Auto-generated catch block 18            e1.printStackTrace(); 19        } catch (IOException e1) { 20            // TODO Auto-generated catch block 21            e1.printStackTrace(); 22        } 23        OutputStream outputStream = null; 24        Scanner sc = new Scanner(System.in);  25        System.out.println("请输入姓名:"); 26        yname=sc.nextLine(); 27        String message=yname+"进入了聊天室"; 28        try { 29            s.getOutputStream().write(message.getBytes("UTF-8")); 30            outputStream = s.getOutputStream(); 31            inStream = s.getInputStream(); 32        } catch (UnsupportedEncodingException e1) { 33            // TODO Auto-generated catch block 34            e1.printStackTrace(); 35        } catch (IOException e1) { 36            // TODO Auto-generated catch block 37            e1.printStackTrace(); 38        } 39 40        try{ 41            rth.start(); 42 43            while(true){     44                mess = sc.nextLine(); 45                String m="[-.-]"+yname+":"+mess; 46                if(mess.equals("bye")){ 47                    break; 48                } 49                if(mess.equals("[聊天记录]")){ 50                    System.out.println("--------本地聊天记录start--------"); 51                    readFile(yname+".txt"); 52                    System.out.println("--------本地聊天记录end--------"); 53                    //mess = null; 54                } 55                if(!mess.equals("[聊天记录]")){ 56                    s.getOutputStream().write(m.getBytes("UTF-8")); 57                }    58            } 59        }catch (Exception e) { 60 61        } 62        String bye=yname+"退出了聊天室"; 63        try { 64            s.getOutputStream().write(bye.getBytes("UTF-8")); 65            rth.interrupt(); 66            inStream.close(); 67            outputStream.close(); 68            s.close(); 69        } catch (UnsupportedEncodingException e) { 70            // TODO Auto-generated catch block 71            e.printStackTrace(); 72        } catch (IOException e) { 73            // TODO Auto-generated catch block 74            e.printStackTrace(); 75        }    76 77        return; 78    } 79 80    public static class RecvThread extends Thread{ 81        @Override 82        public void run() { 83            // TODO Auto-generated method stub 84            while(true){ 85                if(mess.equals("bye")){ 86                    break; 87                } 88                try {    89                    if (inStream.available() > 0) 90                    { 91                        byte[]  recvByte = new byte[1024*2]; 92                        int recvCount= inStream.read(recvByte); 93 94                        if (recvCount < 0) 95                        { 96                            System.out.println(" ");     97                        }else{ 98                            String str = byteArrayToStr(recvByte); 99                            //String str2 = new String(recvByte,"ANSI"); 100                            System.out.println(str.trim()); 101                            saveFile(str,yname+".txt"); 102                            //System.out.println(new String(br.readLine().getBytes(),"UTF-8")); 103                        }           104                    }   105                }  106                catch (Exception e) { 107 108                } 109            } 110        } 111    } 112 113    public static String byteArrayToStr(byte[] byteArray) { 114        if (byteArray == null) { 115            return null; 116        } 117        String str = null; 118        try { 119            str = new String(byteArray,"UTF-8"); 120        } catch (UnsupportedEncodingException e) { 121            // TODO Auto-generated catch block 122            e.printStackTrace(); 123        } 124        return str; 125    } 126    public static void readFile(String fileName){ 127        //FileReader fr=null; 128        //File file;     129        BufferedReader buf = null; 130        String str=null; 131        //file = new File("C:\\Users\\Aen\\Desktop\\Chat\\"+fileName); 132        String filen="C:\\Users\\Aen\\Desktop\\Chat\\"+fileName; 133        try { 134            //fr = new FileReader(file); 135            try { 136                buf=new BufferedReader(new InputStreamReader(new FileInputStream(filen),"UTF-8")); 137            } catch (UnsupportedEncodingException e1) { 138                // TODO Auto-generated catch block 139                e1.printStackTrace(); 140            } 141            try { 142                while((str = buf.readLine())!=null){ 143                    System.out.println(str.trim()); 144                } 145            } catch (IOException e) { 146                // TODO Auto-generated catch block 147                e.printStackTrace(); 148            } 149        } catch (FileNotFoundException e) { 150            // TODO Auto-generated catch block 151            e.printStackTrace(); 152        }finally{ 153            if(buf!=null){ 154                try { 155                    buf.close(); 156                } catch (IOException e) { 157                    // TODO Auto-generated catch block 158                    e.printStackTrace(); 159                } 160            } 161        } 162 163    } 164    //保存本地文件 165    public static void saveFile(String content, String fileName){ 166        //FileWriter fw=null; 167        File file;      168        BufferedWriter bw =null; 169        try {       170           file = new File("C:\\Users\\Aen\\Desktop\\Chat\\"+fileName); 171           String filen="C:\\Users\\Aen\\Desktop\\Chat\\"+fileName; 172           ////fop = new FileOutputStream(file,true); 173           if (!file.exists()) { 174            file.createNewFile(); 175           } 176           //fw = new FileWriter(file,true); 177           bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (filen,true),"UTF-8")); 178 179           //BufferedWriter bw = new BufferedWriter(fw); 180           bw.write(content); 181           bw.newLine(); 182           //bw.close();    183        } catch (IOException e) { 184           e.printStackTrace(); 185        } finally { 186            if(bw!=null){ 187                try { 188                    bw.close(); 189                } catch (IOException e) { 190                    // TODO Auto-generated catch block 191                    e.printStackTrace(); 192                } 193            } 194        } 195    } 196}

Android端

Android源码过长,不再展示了,同时也有简单的界面。

小结

小项目用了C和java,同时也可以会点Android,笔者不才恰好这几个都会点,到后来C懂得更多一点,这个代码涵盖了网络编程,线程,文件操作,更好的学习一些编程的语言的基本知识。

如果你想获取源码,公众号内回复”聊天室“获取

图片