It 18 Palm Job _java Foundation 16th Day _gui/socket

Source: Internet
Author: User


Refer to the video and write a chat program.

Knowledge Point Analysis:

Socket + GUI + IO = Simplified version of QQ

------------------------------

1.GUI

2.Socket

Serversocket:port + Accept


Socket sock = accept ();

Update window


Receiving data from the client

New Thread () {

Run () {

Sock. getInputStream ();

....

Update window

}

}.start ()


3. Complete the ServerSocket push message to all clients in a sub-thread.

List<outputstream> ... =;

4. Push the contact list to all clients.








-------------------------------------------------------------------------------------------

Package Com.it18zhang.QQDemo;


public class App {


public static void Main (string[] args) {

Create window

Mywindow w = new Mywindow ();

Messaging server

Messageserver Server = new Messageserver (w);

Start the messaging server

Server.start (1234);

}


}

Package Com.it18zhang.QQDemo;


Import Java.io.BufferedReader;

Import Java.io.BufferedWriter;

Import Java.io.InputStreamReader;

Import Java.io.OutputStreamWriter;

Import Java.net.Socket;


public class Clientdemo {


public static void Main (string[] args) throws Exception {

Socket s = new socket ("localhost", 1234);

BufferedWriter bw = new BufferedWriter (New OutputStreamWriter (S.getoutputstream (), "GBK"));

Bw.write ("TCP hello!");

S.close ();

}


}

Package Com.it18zhang.QQDemo;


Import Java.awt.event.WindowAdapter;

Import java.awt.event.WindowEvent;

Import java.util.ArrayList;

Import Java.util.HashSet;

Import java.util.List;

Import Java.util.Set;


Import Javax.swing.JButton;

Import Javax.swing.JFrame;

Import javax.swing.JList;

Import javax.swing.JTable;

Import Javax.swing.JTextArea;

Import Javax.swing.table.AbstractTableModel;

Import Javax.swing.table.TableModel;


public class Mywindow extends JFrame {


Private static final long serialversionuid = 6142786986925220872L;


Historical records

Private JTextArea tahistory;

Send content

Private JTextArea tacontent;

Send button

Private JButton btnsend;

Contact List

Private JList listcontacts;

Private JTable table;


Initialize the form

Public Mywindow () {

INI ();

}


Initialize action

private void Ini () {

Set the boundary size, position

This.setsize (600, 400);

This.setlocation (200, 200);


Set to Absolute layout

This.setlayout (NULL);


Set up a Contact table

Table = new JTable ();

Table.setbounds (500, 0, 100, 400);

This.add (table);


Set the chat history area

Tahistory = new JTextArea ();

Tahistory.seteditable (FALSE);

Tahistory.setbounds (0, 0, 480, 300);

This.add (tahistory);


This.setvisible (TRUE);


Adding Listener Events

This.addwindowlistener (New Windowadapter () {

public void windowclosed (WindowEvent e) {

System.exit (-1);

}

});


}

/**

* Refresh Contacts

*/

public void Refreshcontacts (final list<string> clients) {

set<string> set = new hashset<string> (clients);

Final list<string> newclients = new arraylist<string> (set);

TableModel Datamodel = new Abstracttablemodel () {

Public Object getvalueat (int row, int col) {

return Newclients.get (Row);

}

public int GetRowCount () {

return Newclients.size ();

}

public int getColumnCount () {

return 1;

}

};

Table.setmodel (Datamodel);

}

/**

* Update Chat History

*/

public void Updatehistory (string addr, string line) {

Original

String old = Tahistory.gettext ();

StringBuilder builder = new StringBuilder ();

Builder.append (old);

Builder.append ("\ r \ n");

Builder.append (addr);

Builder.append ("\ r \ n");

Builder.append (line);

Builder.append ("\ r \ n");

Update Chat Area

Tahistory.settext (Builder.tostring ());

}


}

Package Com.it18zhang.QQDemo;


Import java.net.InetAddress;

Import Java.net.ServerSocket;

Import Java.net.Socket;

Import java.util.ArrayList;

Import java.util.List;


/**

* Message Server

*/

public class Messageserver {

Defines a collection of clients,

Private list<string> clients = new arraylist<string> ();

Private Mywindow window;

Public messageserver (Mywindow window) {

This.window = window;

}

Start the server

public void start (int port) {

try {

ServerSocket ss = new ServerSocket (port);

SYSTEM.OUT.PRINTLN ("Server started up");

InetAddress remaddr;

int remport;

while (true) {

Final Socket sock = Ss.accept ();

System.out.println (socketutil.getaddr (sock) + ": Connected");

New Messagereceiverthread (Window,sock). Start ();

REMADDR = Sock.getinetaddress ();

Remport = Sock.getport ();

Adding Client Objects

Clients.add (socketutil.getaddr (sock));

Refresh List

Window.refreshcontacts (clients);

}

} catch (Exception e) {

E.printstacktrace ();

}

}

}

Package Com.it18zhang.QQDemo;


Import Java.io.BufferedReader;

Import Java.io.InputStreamReader;

Import Java.net.Socket;


/**

* Message Receive Thread

*/

public class Messagereceiverthread extends Thread {

Private Mywindow window;

Private Socket sock;

Public messagereceiverthread (Mywindow window, Socket sock) {

This.window = window;

This.sock = sock;

}

public void Run () {

while (true) {

try {

BufferedReader br = new BufferedReader (New InputStreamReader (Sock.getinputstream (), "GBK"));

String line = null;

while (line = Br.readline ()) = null) {

Window.updatehistory (socketutil.getaddr (sock), line); //Update History list

}

} catch (Exception e) {

E.printstacktrace ();

}

}

}

}

Package Com.it18zhang.QQDemo;


Import Java.net.Socket;


public class Socketutil {

/**

* Return address string

*/

public static String Getaddr (Socket sock) {

String IP = sock.getinetaddress (). gethostaddress ();

String ip0 = ip.substring (Ip.lastindexof (".") +1);

Return ip0+ ":" +sock.getport ();

}

}


This article from "Rookie Achievement Data Road" blog, reproduced please contact the author!

It 18 Palm Job _java Foundation 16th Day _gui/socket

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.