码迷,mamicode.com
首页 > 其他好文 > 详细

网络编程两人聊天

时间:2016-01-19 10:25:37      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

ServerDemo

import java.io.* ;
import java.net.* ;
public class serverDemo {
    public static void main(String [] args){
        ServerSocket serverSocket = null ;
        Socket socket = null ;
        String line ;
        try{
            serverSocket = new ServerSocket (5555) ;
            socket = serverSocket.accept();
            System.out.println("Success") ;
            System.out.println();
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))  ;
            BufferedReader sin = new BufferedReader (new InputStreamReader(System.in));
            PrintWriter os = new PrintWriter(socket.getOutputStream());
            System.out.println("From Client: " + in.readLine()) ;
            line = sin.readLine();
            while(!line.equals("bye")) {
                os.println(line) ;
                os.flush() ;
                System.out.println("From Client:" + in.readLine()) ;
                line = sin.readLine();
            }
            in.close() ;
            sin.close() ;
            os.close() ;
            socket.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace() ;
        }
    }
}

ClientDemo。

 

import java.net.* ;
import java.io.*;
public class ClientDemo {
    public static void main(String [] args){
        
        try{
            Socket socket = new Socket("192.168.1.116",5555) ;
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)) ;
            BufferedReader in = new BufferedReader (new InputStreamReader(socket.getInputStream())) ;
            PrintWriter os = new PrintWriter(socket.getOutputStream()) ;
            String line ;
            line = sin.readLine() ;
            while(!line.equals("bye")){
                os.println(line) ;
                os.flush() ;
                System.out.println("Client:" + line); 
                System.out.println("From Server:" + in.readLine()) ;
                line = sin.readLine() ;
                
            }
            os.close();
            sin.close() ;
            in.close();
            socket.close() ;
        }catch (Exception e) {
            e.printStackTrace() ;
        }
    }
}

 

网络编程两人聊天

标签:

原文地址:http://www.cnblogs.com/da-peng/p/5141292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!