A chat program

Source: Internet
Author: User
import java.io.*;import java.net.*;class Listen implements Runnable{Socket s;Listen(Socket s){this.s=s;}public void run(){String ip=s.getInetAddress().getHostAddress();while(true){try{BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));String str=br.readLine();System.out.println(ip+"Client Say:");System.out.println(str);}catch (Exception e){}}}}class Write implements Runnable{Socket s;Write(Socket s){this.s=s;}public void run(){try{while(true){PrintWriter out=new PrintWriter(s.getOutputStream(),true);BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));String str1=br1.readLine();out.println(str1);}}catch(Exception e){}}}public class Server {public static void main(String[] args)throws SocketException,IOException  {ServerSocket sc=new ServerSocket(12000);Socket ss=sc.accept();new Thread(new Listen(ss)).start();new Thread(new Write(ss)).start();}}

Import java. io. *; import java.net. *; class Listen1 implements Runnable {Socket s; Listen1 (Socket s) {this. s = s;} public void run () {while (true) {try {BufferedReader br = new BufferedReader (new InputStreamReader (s. getInputStream (); String str = br. readLine (); System. out. println ("Server Say:"); System. out. println (str);} catch (Exception e) {}}} class Write1 implements Runnable {Socket s; Write1 (Socket s) {this. s = s;} public void run () {try {while (true) {PrintWriter out = new PrintWriter (s. getOutputStream (), true); BufferedReader br1 = new BufferedReader (new InputStreamReader (System. in); String str1 = br1.readLine (); out. println (str1) ;}} catch (Exception e) {}} public class Client {public static void main (String [] args) throws Exception {Socket s = new Socket ("172.16.99.99", 12000); new Thread (new Listen1 (s )). start (); // The Thread for reading information new Thread (new Write1 (s )). start (); // message sending thread }}

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.