Android-use socket communication to establish Network Chat Room 1, android-socket

Source: Internet
Author: User

Android-use socket communication to establish Network Chat Room 1, android-socket

First, create a server program:

1. MyServerSocket. java

package com.test.test;public class MyServerSocket {public static void main(String[] args) {new ServerListener().start();}}


2. ServerListener. java is used to listen for port connections

Package com. test. test; import java. io. IOException; import java.net. serverSocket; import java.net. socket; import javax. swing. JOptionPane; public class ServerListener extends Thread {public void run () {try {ServerSocket serverSocket = new ServerSocket (12345); while (true) {Socket socket Socket = serverSocket. accept (); JOptionPane. showMessageDialog (null, "a client is connected to port 12345! "); New ChatSocket (socket). start () ;}} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}


3. ChatSocket. java

package com.test.test;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.Socket;public class ChatSocket extends Thread {Socket socket;public ChatSocket(Socket s){this.socket=s;}public void out(String out){try {socket.getOutputStream().write(out.getBytes("UTF-8"));} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void run() {int count=0;while(true){count++;out("loop+"+count);}}}


Run MyServerSocket. java:

Open the DOS interface and enter telnet localhost 12345.

 

Click OK below:

 

Open a client and enter the following command:

It can be seen that each client has an independent thread for processing.

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.