Java基于TCP如何实现简单聊天程序(java,tcp,开发技术)

时间:2024-05-08 01:59:30 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

一、如何实现TCP通信

要实现TCP通信需要创建一个服务器端程序和一个客户端程序,为了保证数据传输的安全性,首先需要实现服务器端程序,然后在编写客户端程序。

在本机运行服务器端程序,在远程机运行客户端程序

本机的IP地址:192.168.129.222

Java基于TCP如何实现简单聊天程序

远程机的IP地址:192.168.214.213

Java基于TCP如何实现简单聊天程序

二、编写C/S架构聊天程序

1.编写服务器端程序 - Server.java

在net.hw.network包里创建Server类

Java基于TCP如何实现简单聊天程序

packagenet.hw.network;importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.ServerSocket;importjava.net.Socket;/***功能:服务器端*作者:华卫*日期:2022年03月18日*/publicclassServerextendsJFrame{staticfinalintPORT=8136;staticfinalStringHOST_IP="192.168.129.222";privateJPanelpanel1,panel2;privateJTextAreatxtContent,txtInput,txtInputIP;privateJScrollPanepanContent,panInput;privateJButtonbtnClose,btnSend;privateServerSocketserverSocket;privateSocketsocket;privateDataInputStreamnetIn;privateDataOutputStreamnetOut;publicstaticvoidmain(String[]args){newServer();}publicServer(){super("服务器");//创建组件panel1=newJPanel();panel2=newJPanel();txtContent=newJTextArea(15,60);txtInput=newJTextArea(3,60);panContent=newJScrollPane(txtContent,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);panInput=newJScrollPane(txtInput,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);btnClose=newJButton("关闭");btnSend=newJButton("发送");//添加组件getContentPane().add(panContent,"Center");getContentPane().add(panel1,"South");panel1.setLayout(newGridLayout(0,1));panel1.add(panInput);panel1.add(panel2);panel2.add(btnSend);panel2.add(btnClose);//设置组件属性txtContent.setEditable(false);txtContent.setFont(newFont("宋体",Font.PLAIN,13));txtInput.setFont(newFont("宋体",Font.PLAIN,15));txtContent.setLineWrap(true);txtInput.setLineWrap(true);txtInput.requestFocus();setSize(450,350);setLocation(50,200);setResizable(false);setVisible(true);//等候客户请求 try{txtContent.append("服务器已启动...\n");serverSocket=newServerSocket(PORT);txtContent.append("等待客户请求...\n");socket=serverSocket.accept();txtContent.append("连接一个客户。\n"+socket+"\n");netIn=newDataInputStream(socket.getInputStream());netOut=newDataOutputStream(socket.getOutputStream());}catch(IOExceptione1){e1.printStackTrace();}///注册监听器,编写事件代码 txtContent.addMouseMotionListener(newMouseMotionAdapter(){publicvoidmouseMoved(MouseEvente){displayClientMsg();}});txtInput.addMouseMotionListener(newMouseMotionAdapter(){publicvoidmouseMoved(MouseEvente){displayClientMsg();}});panel2.addMouseMotionListener(newMouseMotionAdapter(){publicvoidmouseMoved(MouseEvente){displayClientMsg();}});txtInput.addKeyListener(newKeyAdapter(){publicvoidkeyTyped(KeyEvente){displayClientMsg();}});txtInput.addFocusListener(newFocusAdapter(){publicvoidfocusGained(FocusEvente){displayClientMsg();}});btnSend.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){try{StringserverMsg=txtInput.getText();if(!serverMsg.trim().equals("")){txtContent.append("服务器>"+serverMsg+"\n");netOut.writeUTF(serverMsg);}else{JOptionPane.showMessageDialog(null,"不能发送空信息!","服务器",JOptionPane.WARNING_MESSAGE);}txtInput.setText("");txtInput.requestFocus();}catch(IOExceptionie){ie.printStackTrace();}}});btnClose.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){try{netIn.close();netOut.close();socket.close();serverSocket.close();}catch(IOExceptione){e.printStackTrace();}System.exit(0);}});addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){try{netIn.close();netOut.close();socket.close();serverSocket.close();}catch(IOExceptionie){ie.printStackTrace();}System.exit(0);}publicvoidwindowActivated(WindowEvente){txtInput.requestFocus();}});}//显示客户端信息voiddisplayClientMsg(){try{if(netIn.available()>0){StringclientMsg=netIn.readUTF();txtContent.append("客户端>"+clientMsg+"\n");}}catch(IOExceptione1){e1.printStackTrace();}}}

2.编写客户端程序 - Client.java

在net.hw.network包里创建Client类

Java基于TCP如何实现简单聊天程序

packagenet.hw.network;importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.InetAddress;importjava.net.Socket;/***功能:客户端*作者:华卫*日期:2022年03月18日*/publicclassClientextendsJFrame{privateJPanelpanel1,panel2;privateJTextAreatxtContent,txtInput;privateJScrollPanepanContent,panInput;privateJButtonbtnClose,btnSend;privateSocketsocket;privateDataInputStreamnetIn;privateDataOutputStreamnetOut;publicstaticvoidmain(String[]args){newClient();}publicClient(){super("客户端");//创建组件panel1=newJPanel();panel2=newJPanel();txtContent=newJTextArea(15,60);txtInput=newJTextArea(3,60);panContent=newJScrollPane(txtContent,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);panInput=newJScrollPane(txtInput,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);btnClose=newJButton("关闭");btnSend=newJButton("发送");//添加组件getContentPane().add(panContent,"Center");getContentPane().add(panel1,"South");panel1.setLayout(newGridLayout(0,1));panel1.add(panInput);panel1.add(panel2);panel2.add(btnSend);panel2.add(btnClose);//设置组件属性txtContent.setEditable(false);txtContent.setFont(newFont("宋体",Font.PLAIN,13));txtInput.setFont(newFont("宋体",Font.PLAIN,15));txtContent.setLineWrap(true);txtInput.setLineWrap(true);txtInput.requestFocus();setSize(450,350);setLocation(550,200);setResizable(false);setVisible(true);//连接服务器try{txtContent.append("连接服务器...\n");socket=newSocket(Server.HOST_IP,Server.PORT);txtContent.append("连接服务器成功。\n"+socket+"\n");netIn=newDataInputStream(socket.getInputStream());netOut=newDataOutputStream(socket.getOutputStream());}catch(IOExceptione1){JOptionPane.showMessageDialog(null,"服务器连接失败!\n请先启动服务器程序!","客户端",JOptionPane.ERROR_MESSAGE);System.exit(1);}///注册监听器,编写事件代码txtContent.addMouseMotionListener(newMouseMotionAdapter(){publicvoidmouseMoved(MouseEvente){displayServerMsg();}});txtInput.addMouseMotionListener(newMouseMotionAdapter(){publicvoidmouseMoved(MouseEvente){displayServerMsg();}});panel2.addMouseMotionListener(newMouseMotionAdapter(){publicvoidmouseMoved(MouseEvente){displayServerMsg();}});txtInput.addKeyListener(newKeyAdapter(){publicvoidkeyTyped(KeyEvente){displayServerMsg();}});txtInput.addFocusListener(newFocusAdapter(){publicvoidfocusGained(FocusEvente){displayServerMsg();}});btnSend.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){try{StringclientMsg=txtInput.getText();if(!clientMsg.trim().equals("")){netOut.writeUTF(clientMsg);txtContent.append("客户端>"+clientMsg+"\n");}else{JOptionPane.showMessageDialog(null,"不能发送空信息!","客户端",JOptionPane.WARNING_MESSAGE);}txtInput.setText("");txtInput.requestFocus();}catch(IOExceptionie){ie.printStackTrace();}}});btnClose.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){try{netIn.close();netOut.close();socket.close();}catch(IOExceptionie){ie.printStackTrace();}System.exit(0);}});addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){try{netIn.close();netOut.close();socket.close();}catch(IOExceptionie){ie.printStackTrace();}System.exit(0);}publicvoidwindowActivated(WindowEvente){txtInput.requestFocus();}});}//显示服务端信息voiddisplayServerMsg(){try{if(netIn.available()>0){StringserverMsg=netIn.readUTF();txtContent.append("服务器>"+serverMsg+"\n");}}catch(IOExceptione1){e1.printStackTrace();}}}

3.测试服务器端与客户端能否通信

在本机[192.168.129.222]上启动服务器端

Java基于TCP如何实现简单聊天程序

在远程机[192.168.214.213]上启动客户端

Java基于TCP如何实现简单聊天程序

显示连接服务器[192.168.129.222]成功,切换到服务器端查看,显示连接了一个客户[192.168.214.213]

Java基于TCP如何实现简单聊天程序

此时,服务器端和客户端就可以相互通信了

Java基于TCP如何实现简单聊天程序

4.程序优化思路 - 服务器端采用多线程

其实,很多服务器端程序都是允许被多个应用程序访问的,例如门户网站可以被多个用户同时访问,因此服务器端都是多线程的。

Java基于TCP如何实现简单聊天程序

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Java基于TCP如何实现简单聊天程序的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:php如何计算页面运行加载时间下一篇:

10 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18