android--Creating a network chat room using socket communication 1

Source: Internet
Author: User

First establish the server-side program:

1.myserversocket.java

Package Com.test.test;public class myServerSocket {public static void main (string[] args) {new Serverlistener (). Start ();}}


2.serverlistener.java for listening to 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=serversocket.accept (); Joptionpane.showmessagedialog (NULL, "There is a client 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 Au To-generated catch Blocke.printstacktrace ();}} public void Run () {int Count=0;while (true) {count++;out ("loop+" +count);}}}


Run Myserversocket.java:

Open DOS interface input telnet localhost 12345 display

Click OK below:

Then open a client input command:

It can be seen that each client has a separate thread to handle.

android--Creating a network chat room using socket communication 1

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.