2018.4.28 Java-based chat system (with perfect)

Source: Internet
Author: User

Java Chat System 1.Socket class
Socket(InetAddress address, int port) 创建一个流套接字并将其连接到指定 IP 地址的指定端口号。Socket(String host, int port) 创建一个流套接字并将其连接到指定主机上的指定端口号。Socket(InetAddress address, int port, InetAddress localAddr, int localPort) 创建一个套接字并将其连接到指定远程地址上的指定远程端口。Socket(String host, int port, InetAddress localAddr, int localPort) 创建一个套接字并将其连接到指定远程主机上的指定远程端口。close() 关闭此套接字。connect(SocketAddress endpoint) 将此套接字连接到服务器。connect(SocketAddress endpoint, int timeout) 将此套接字连接到服务器,并指定一个超时值。getInetAddress() 返回套接字连接的地址。getInputStream() 返回此套接字的输入流。getLocalPort() 返回此套接字绑定到的本地端口。getOutputStream() 返回此套接字的输出流。getPort() 返回此套接字连接到的远程端口。
2.ServerSocket class
ServerSocket(int port) 创建绑定到特定端口的服务器套接字。accept() 侦听并接受到此套接字的连接。getInetAddress() 返回此服务器套接字的本地地址。Socket编程步骤服务器端创建ServerSocket对象,调用accept方法返回Socket对象客户端创建Socket对象,通过端口连接到服务器客户端、服务器端都使用Socket中的getInputStream方法和getOutputStream方法获得输入流和输出流,进一步进行数据读写操作(InetAddress用来描述主机地址;Socket用来创建两台主机之间的连接;ServerSocket用来侦听来自客户端的请求;Socket通常称作“套接字”,通常通过“套接字”向网络发出请求或者应答网络请求。)
3. Steps to implement:
   第一步: ChatUtil工具类:把一些常用的常量放进来    第二步:Server开启服务    第三步:ClientSocket连接服务器的socket    第四步:CHatFrame(添加两个属性(name,sex))2.添加了getSocket方法    第五步:LoginFrame设置了默认值  处理性别获得socket对象
package com.lanqiao.demo2;/** * 工具类 * @author qichunlin * */public final class ChatUtil {    //地址    public static final String ADDRESS = "localhost";    //端口    public static final int PORT = 9999;}
  Package Com.lanqiao.demo2;import java.io.ioexception;import Java.net.serversocket;import        java.net.socket;/** * Service-side class * @author Qichunlin */public class Server {public static void main (string[] args) {            try {serversocket ss = new ServerSocket (chatutil.port);            int count = 0;                while (true) {System.out.println ("Waiting for client connections ...");                Socket socket = ss.accept ();                count++;            SYSTEM.OUT.PRINTLN ("There are currently" +count+ "clients entered the chat room"); }} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (        ); }    }}
  Package Com.lanqiao.demo2;import java.io.ioexception;import Java.net.socket;import  java.net.unknownhostexception;/** * Client Socket * @author Qichunlin * */public class Clientsocket {public static socket    Socket        Public Clientsocket () {try {socket = new socket (chatutil.address, chatutil.port);        } catch (Unknownhostexception e) {//TODO auto-generated catch block E.printstacktrace ();        } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }    }}
Package Com.lanqiao.demo2;import Java.awt.container;import Java.awt.flowlayout;import java.awt.GridLayout;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.io.ioexception;import Java.net.Socket ; Import Java.net.unknownhostexception;import Javax.swing.buttongroup;import Javax.swing.jbutton;import Javax.swing.jframe;import Javax.swing.jlabel;import Javax.swing.jpanel;import Javax.swing.JRadioButton;import javax.swing.jtextfield;/** * Chat System Login Interface * @authorqichunlin * */public class Loginframe extends JFrame implements ActionList ener{//define Component JLabel userlab,addrlab,portlab;//label JTextField usertext,addrtext,porttext;//text Box Jradiobutton Radi        oman,radiowoman,radioser;//radio button Buttongroup Group;//Set JButton connectbut,closebut;//button//container JPanel p1,p2,p3;        Public Loginframe () {//Instantiate component P1 = new JPanel ();                P1.setlayout (New FlowLayout (Flowlayout.left));        Userlab = new JLabel ("Name:"); Usertext = new JTEXTFIeld (10);        RadioMan = new Jradiobutton ("male");        Radioman.setselected (TRUE);        Radiowoman = new Jradiobutton ("female");         Radioser = new Jradiobutton ("Confidential");        Add the radio button to group = new Buttongroup ();        Group.add (RadioMan);        Group.add (Radiowoman);                Group.add (Radioser);        To P1, add components (Note: The group does not need to be added to the container) P1.add (Userlab);        P1.add (Usertext);        P1.add (RadioMan);        P1.add (Radiowoman);                        P1.add (Radioser);        P2 = new JPanel ();        P2.setlayout (New FlowLayout (Flowlayout.left));                Addrlab = new JLabel ("Address:");        Addrtext = new JTextField (10);                Addrtext.settext (chatutil.address);        Portlab = new JLabel ("Port:");        Porttext = new JTextField (10);                Porttext.settext (chatutil.port+ "");        Add Components to P2 P2.add (Addrlab);        P2.add (Addrtext);        P2.add (Portlab);                        P2.add (Porttext);      P3 = new JPanel ();  P3.setlayout (New FlowLayout (Flowlayout.center));        Connectbut =new JButton ("Connection");                Bind event "click event" Connectbut.addactionlistener (this);        Closebut = new JButton ("disconnect");        Add components to P3 P3.add (connectbut);                                                P3.add (closebut); Sets the layout mode of the panel (streaming layout) This.getcontentpane (). setlayout (New GridLayout (3,1));//Grid layout//Add components to the panel//1        , get panel Container c = This.getcontentpane ();        Add the P1 container to the panel C.add (p1);        Add the P2 container to the panel c.add (p2);                Add the P3 container to the panel c.add (P3);    Init ();        /** * Initialize form basic information */public void init () {//1, title This.settitle ("Login Interface");        2, size this.setsize (350,200);        3, turn off the amplification function this.setresizable (false);        4, Position this.setlocationrelativeto (null);        5, whether to display this.setvisible (true); 6. Close This.setdefaultcloseoperation (jframe.exit_on_clOSE);    } public static void Main (string[] args) {new loginframe ();        }//Click event Processing @Override public void actionperformed (ActionEvent e) {//Handle selection in gender String sex = "";        if (radiowoman.isselected ()) {sex = "female";        }else if (radioman.isselected ()) {sex = "male";        }else {sex = "confidential";        } System.out.println ("============");        1, hide the current interface "login Interface" this.setvisible (false);    2. Display the chat interface chatframe C = new ChatFrame (Usertext.gettext (), sex);//Login name passed over C.getsocket (); }}
package com.lanqiao.demo2;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;/** * 服务端类 * @author qichunlin */public class Server {    public static void main(String[] args) {        try {            ServerSocket ss = new ServerSocket(ChatUtil.PORT);            int count = 0;            while (true) {                System.out.println("等待客户端连接.......");                Socket socket = ss.accept();                count++;                System.out.println("目前有"+count+"个客户端进入了聊天室");            }                    } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

2018.4.28 Java-based chat system (with perfect)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.