Import java.io.*;
Import Java.net.ServerSocket;
Import Java.net.Socket;
/** * Create by wdful * email:wdful165177@gmail.com * DATE:2017/4/7 * * * * Chat program one thread control to receive a line program-controlled delivery at the same time///Send End
Class Client implements Runnable {private Socket s;
Public Client (Socket s) {this.s = s; @Override public void Run () {while (true) {System.out.println (Thread.CurrentThread () + Client
Send a message: ");
BufferedReader ins = new BufferedReader (new InputStreamReader (system.in));
String str = NULL;
try {str = ins.readline ();
In order to send the data to obtain the output stream in the socket outputstream out = S.getoutputstream ();
Out.write (Str.getbytes ());
if ("886". Equals (str)) {System.out.println (Thread.CurrentThread () + ": Bye");
S.close ();
System.exit (0);
} catch (IOException e) { E.printstacktrace ();
//Get data inputstream in = NULL;
try {in = S.getinputstream ();
byte[] data = new byte[1024];
int len = in.read (data);
System.out.println (Thread.CurrentThread () + "server-side said to the client:");
System.out.println (new String (data, 0, Len));
catch (IOException e) {e.printstacktrace ();
Class Serverclient implements Runnable {private ServerSocket SS;
Private Socket S;
Public Serverclient (ServerSocket ss) {THIS.SS = SS;
@Override public void Run () {System.out.println ("Server start ...");
Establish a service-side socket service and listen on a port//Get Client object try {s = ss.accept (); Connection Status System.out.println ("Connected:" + s.getinetaddress (). Gethostaddress (). toString () + "PORT:" + S.getpor
T ());
catch (IOException e) { E.printstacktrace (); SYSTEM.OUT.PRINTLN ("Get client failed.)
");
} while (true) {try {//Read data InputStream in = S.getinputstream ();
byte[] data = new byte[1024];
int len = in.read (data);
String str = new string (data, 0, Len);
if ("886". Equals (str)) {System.out.println (Thread.CurrentThread () + ": Bye");
Ss.close ();
S.close ();
System.exit (0);
System.out.println (Thread.CurrentThread () + "Client on the server said:");
System.out.println (str);
System.out.println (Thread.CurrentThread () + "service End-to-end message:");
BufferedReader ins = new BufferedReader (new InputStreamReader (system.in));
In order to send the data to obtain the output stream in the socket outputstream out = S.getoutputstream (); Out.write (Ins.readline (). GetBytes ());
catch (IOException e) {e.printstacktrace ();
Class Chatdemo {public static void main (string[] args) throws IOException {//server-side Startup
Serverclient serverclient = new Serverclient (new ServerSocket (10000));
Thread t2 = new Thread (serverclient);
T2.start ();
Client-Initiated clients = new Client (new Socket ("127.0.0.1", 10000);
thread T1 = new thread (client);
T1.start (); }
}