Learn javase TCP/IP protocol and build a simple chat room

Source: Internet
Author: User
Tags thread class

One, TCP/IP protocol

1. TCP/IP protocol including TCP, IPS and UDP
2. Domain name is converted to IP address via DNS server
3, LAN can be IP or host address to find the corresponding host
4, TCP is a reliable connection, low efficiency, and the connection is one-on, TCP, and UDP is unreliable connection, easy to lose data, but high efficiency, and the connection is one-to-many.

Second, port number

1. The port number uniquely identifies an application in the server
2, a server does not allow the presence of two of the same port number of applications
3. Ip:port uniquely determine server application
4. The default port for HTTPS is 443,http for 80,https is an upgraded version of HTTP encryption and decryption

Third, Socket

1, the client application and the port to use the socket connection, for example, the client application compared to home appliances, port IO stream compared to current, then socket is socket, home appliances only plug the wire into the socket to power
2. Use ServerSocket connection between server and port
3, as long as the socket instance has been obtained, there is an IO stream

Four, InetAddress class
public class TestTcp {    public static void main(String[] args) {        try {            InetAddress localHost = InetAddress.getLocalHost();            System.out.println(localHost.getHostName());//获取主机名            System.out.println(localHost.getHostAddress());//获取主机地址            localHost = InetAddress.getByName("baidu.com");            System.out.println(localHost.getHostName());            System.out.println(localHost.getHostAddress());        } catch (UnknownHostException e) {            e.printStackTrace();        }    }}
Five, simple chat room

This chat room includes a server and n clients, the client sends a message to the server, and the server will send the message to other clients other than themselves.
To send a message, you have to have an IO stream, you want the IO stream to have a socket, and who can send messages to who's socket.

The chat room code is as follows:

Import Java.io.*;import java.net.serversocket;import Java.net.socket;import Java.util.arraylist;import Java.util.list;import Java.util.scanner;public class Talktool {}//server class servert{public static void Main (string[] Ar GS) {try {serversocket serversocket = new ServerSocket (9014);//Establish a service-side socket-to-port association System.out.pri            NTLN ("Server started successfully, waiting for client Connection");            list<socket> socketlist = new arraylist<> ();                while (true) {////The main thread is only responsible for client connection socket socket = serversocket.accept ();//Waiting for Client connection (blocking state)                System.out.println ("With Client Connection");                Socketlist.add (socket);            New Thread (New Forwardt (Socket,socketlist)). Start ();        }} catch (IOException e) {e.printstacktrace (); }}}//client class clientt{public static void Main (string[] args) {try {socket socket = new Socket ( "192.168.226.1", 9014);//Establish connection, IP address according to the actual situation set SYSTEM.OUT.PRINTLN ("Client andConnection established by the server);            OutputStream outputstream = Socket.getoutputstream ();            PrintWriter printwriter = new PrintWriter (new OutputStreamWriter (OutputStream), true);            Scanner Scanner = new Scanner (system.in);            The standalone thread is responsible for receiving the message new thread (new Recevet (socket)). Start ();            while (true) {printwriter.println (Scanner.next ());        }} catch (IOException e) {e.printstacktrace ();    }}}//server-side forwarding thread class Forwardt implements runnable{private socket socket;    Private list<socket> socketlist;        Public Forwardt (Socket socket,list<socket>socketlist) {this.socket=socket;    This.socketlist=socketlist; } @Override public void Run () {try {while (true) {InputStream InputStream = sock                Et.getinputstream ();                BufferedReader BufferedReader = new BufferedReader (new InputStreamReader (InputStream)); String msg = BufferedreaDer.readline ();                SYSTEM.OUT.PRINTLN (msg); for (Socket sk:socketlist) {if (Sk!=socket) {//Exclude yourself//Send to other customers                        The socket OutputStream outputstream = Sk.getoutputstream () of other clients must be in the end;                        PrintWriter printwriter = new PrintWriter (new OutputStreamWriter (OutputStream), true);                    PRINTWRITER.PRINTLN (socket+ "said: +msg);        }}}} catch (IOException e) {e.printstacktrace ();    }}}//client receive thread class Recevet implements runnable{private socket socket;    Public Recevet (socket socket) {this.socket=socket; } @Override public void Run () {try {while (true) {InputStream InputStream = sock                Et.getinputstream ();                BufferedReader BufferedReader = new BufferedReader (new InputStreamReader (InputStream)); System.out.println ("The service side Returns "+bufferedreader.readline ()");        }} catch (IOException e) {e.printstacktrace (); }    }}

Learning javase TCP/IP protocol and building a simple chat room

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.