Use Socket in Java to implement chat programs

Source: Internet
Author: User

This chat program is very simple, that is, a program acts as a Server and a program acts as a Client ). The Server waits for the Client to establish a Socket connection with it. Once connected, the Server and Client can communicate. This is a basic program for beginners of Java socket!

Step 1: Start the Server. java main program. Click Connect;

Step 2: Start the Client. java main program. Click Connect.

The Code is as follows: Copy code

Server. java

Import java. awt. event. ActionEvent;
Import java. awt. event. ActionListener;
Import java. awt. event. KeyEvent;
Import java. awt. event. KeyListener;
Import java. io. DataInputStream;
Import java. io. DataOutputStream;
Import java. io. IOException;
Import java.net. ServerSocket;
Import java.net. Socket;

Import javax. swing. JButton;
Import javax. swing. JFrame;
Import javax. swing. JOptionPane;
Import javax. swing. JScrollPane;
Import javax. swing. JTextArea;
Import javax. swing. JTextField;
Import javax. swing. UIManager;


Public class Server {
Public static void initUIManager (){
Try {
UIManager. setLookAndFeel (UIManager. getSystemLookAndFeelClassName ());
} Catch (Exception e ){
System. err. println ("failed to get System appearance:" + e );
}
}
Public static void main (String [] args ){
InitUIManager ();
New ServerFrame ();
}
}

Class ServerFrame extends JFrame implements Runnable, ActionListener, KeyListener {
Private static final long serialVersionUID = 1969584312152336324L;
JScrollPane textPane;
JTextArea areaText;
JTextField fieldMsg;
JButton butSend;
JButton butConnect;
 
ServerSocket socket;
Socket you;
DataInputStream in;
DataOutputStream out;
Thread thread;
 
Public static int WIDTH = 500;
Public static int size = 400;
Public static String title = "Server: Click Connect to start accepting Client requests ";
 
Public ServerFrame (){
Init ();
SetTitle (title );
SetSize (WIDTH, HEIGHT );
SetLocationRelativeTo (null );
SetVisible (true );
Setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
}
Public void init (){
SetLayout (null );
AreaText = new JTextArea ();
AreaText. setLineWrap (true );
TextPane = new JScrollPane (areaText );

ButSend = new JButton ("Send ");
FieldMsg = new JTextField (255 );
ButSend. addActionListener (this );
ButConnect = new JButton ("Connect ");
ButConnect. addActionListener (this );

TextPane. setBounds (5, 5, WIDTH-25, HEIGHT-80 );
FieldMsg. setBounds (5, HEIGHT-70, WIDTH-220, 24 );
ButSend. setBounds (WIDTH-195, HEIGHT-70, 80, 24 );
ButConnect. setBounds (WIDTH-100, HEIGHT-70, 80, 24 );

FieldMsg. addKeyListener (this );

Add (textPane );
Add (butSend );
Add (fieldMsg );
Add (butConnect );
Thread = new Thread ();
}
Public void startSocket (){
Try {
AreaText. append ("Waiting for clients... n ");
Socket = new ServerSocket (4331 );
You = socket. accept ();
AreaText. append ("A Client is currently accepted by server... n ");
In = new DataInputStream (you. getInputStream ());
Out = new DataOutputStream (you. getOutputStream ());
If (! Thread. isAlive ()){
Thread = new Thread (this );
}
Thread. start ();
} Catch (Exception e ){
System. out. println (e );
Try {
Socket = new ServerSocket (4331 );
} Catch (IOException e1 ){
E1.printStackTrace ();
}
}
}
 
Public void send (){
String msg = fieldMsg. getText (). trim ();
If (msg. isEmpty ()){
JOptionPane. showMessageDialog (this, "Please input you message before sending .");
Return;
}
AreaText. append ("Server:" + msg + "n ");
Try {
Out. writeUTF (msg );
} Catch (Exception e ){
E. printStackTrace ();
}
}

@ Override
Public void actionreceivmed (ActionEvent arg0 ){
If (arg0.getSource () = butSend ){
Send ();
}
Else if (arg0.getSource () = butConnect ){
StartSocket ();
}
}
@ Override
Public void run (){
If (Thread. currentThread () = thread ){
String msg = null;
While (true ){
Try {
Msg = in. readUTF ();
AreaText. append ("Client:" + msg + "n ");
} Catch (IOException e ){
E. printStackTrace ();
Try {
Socket = new ServerSocket (4331 );
} Catch (IOException e1 ){
E1.printStackTrace ();
}
Break;
}
}
}
}
 
@ Override
Public void keyPressed (KeyEvent arg0 ){
If (arg0.getKeyCode () = KeyEvent. VK_ENTER ){
Send ();
}
}

@ Override
Public void keyReleased (KeyEvent arg0 ){

}

@ Override
Public void keyTyped (KeyEvent arg0 ){

}
 
}

Client. java

Import java. awt. event. ActionEvent;
Import java. awt. event. ActionListener;
Import java. awt. event. KeyEvent;
Import java. awt. event. KeyListener;
Import java. io .*;
Import java.net .*;
Import javax. swing. JButton;
Import javax. swing. JFrame;
Import javax. swing. JOptionPane;
Import javax. swing. JScrollPane;
Import javax. swing. JTextArea;
Import javax. swing. JTextField;
Import javax. swing. UIManager;

Public class Client {
Public static void initUIManager (){
Try {
UIManager. setLookAndFeel (UIManager. getSystemLookAndFeelClassName ());
} Catch (Exception e ){
System. err. println ("failed to get System appearance:" + e );
}
}
 
Public static void main (String [] args ){
InitUIManager ();
New ClientFrame ();
}
}

Class ClientFrame extends JFrame implements Runnable, ActionListener, KeyListener {

Private static final long serialVersionUID = 8518637966119429018l;
 
JScrollPane textPane;
JTextArea areaText;
JTextField fieldMsg;
JButton butSend;
JButton butConnect;
 
Socket socket;
DataInputStream in;
DataOutputStream out;
 
Thread thread;
 
Public static int WIDTH = 500;
Public static int size = 400;
Public static String title = "Client ";
 
Private static final String IP_ADDRESS = "127.0.0.1 ";
 
Public ClientFrame (){
Init ();
SetTitle (title );
SetSize (WIDTH, HEIGHT );
SetLocationRelativeTo (null );
SetVisible (true );
Setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
}
 
Public void init (){
SetLayout (null );
AreaText = new JTextArea ();
AreaText. setLineWrap (true );
TextPane = new JScrollPane (areaText );

ButSend = new JButton ("Send ");
ButSend. addKeyListener (this );
FieldMsg = new JTextField (255 );
ButSend. addActionListener (this );
ButConnect = new JButton ("Connect ");
ButConnect. addActionListener (this );

TextPane. setBounds (5, 5, WIDTH-25, HEIGHT-80 );
FieldMsg. setBounds (5, HEIGHT-70, WIDTH-220, 24 );
ButSend. setBounds (WIDTH-195, HEIGHT-70, 80, 24 );
ButConnect. setBounds (WIDTH-100, HEIGHT-70, 80, 24 );

Add (textPane );
Add (butSend );
Add (fieldMsg );
Add (butConnect );

FieldMsg. addKeyListener (this );

Socket = new Socket ();
Thread = new Thread (this );
}
 
Public void startSocket (){
Try {
If (! Socket. isConnected ()){
InetAddress address = InetAddress. getByName (IP_ADDRESS );
InetSocketAddress socketAddress = new InetSocketAddress (address, 4331 );
Socket. connect (socketAddress );
In = new DataInputStream (socket. getInputStream ());
Out = new DataOutputStream (socket. getOutputStream ());
ButSend. setEnabled (true );
If (! (Thread. isAlive ())){
Thread = new Thread (this );
}
Thread. start ();
}
} Catch (Exception e ){
System. out. println (e );
Socket = new Socket ();
}
}
 
Public void send (){
String msg = fieldMsg. getText (). trim ();
If (msg. isEmpty ()){
JOptionPane. showMessageDialog (this, "Please input you message before sending .");
Return;
}
AreaText. append ("Client:" + msg + "n ");
Try {
Out. writeUTF (msg );
} Catch (Exception e ){
E. printStackTrace ();
}
}

@ Override
Public void actionreceivmed (ActionEvent arg0 ){
If (arg0.getSource () = butSend ){
Send ();
}
Else if (arg0.getSource () = butConnect ){
StartSocket ();
}
}
@ Override
Public void run (){
If (Thread. currentThread () = thread ){
String msg = null;
While (true ){
Try {
Msg = in. readUTF ();
AreaText. append ("Server:" + msg + "n ");
} Catch (IOException e ){
E. printStackTrace ();
Socket = new Socket ();
Break;
}
}
}
}

@ Override
Public void keyPressed (KeyEvent arg0 ){
If (arg0.getKeyCode () = KeyEvent. VK_ENTER ){
Send ();
}
}

@ Override
Public void keyReleased (KeyEvent arg0 ){

}

@ Override
Public void keyTyped (KeyEvent arg0 ){

}
 
}

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.