码迷,mamicode.com
首页 > 编程语言 > 详细

极简易版专家聊天程序--JAVA练手

时间:2015-05-10 12:40:49      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

呵呵,用JAVA包开发SOCKET连接,是很简单的呢~~~

DailyAdviceServer.java

import java.io.*;
import java.net.*;

public class DailyAdviceServer {
    
    String[] adviceList = {"Take smaller bites", "Go for the tight jeans", "代码写得好,要饭要到老", "You might want to rethink"};
    
    public void go() {
        try {
            ServerSocket serverSock = new ServerSocket(4242);
            
            while(true) {
                Socket sock = serverSock.accept();
                PrintWriter writer = new PrintWriter(sock.getOutputStream());
                String advice = getAdvice();
                writer.println(advice);
                writer.close();
                System.out.println(advice);
            }
        } catch(IOException ex) {
            ex.printStackTrace();
        } finally {
            //
        }
    }
    private String getAdvice() {
        int random = (int) (Math.random() * adviceList.length);
        return adviceList[random];
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DailyAdviceServer server = new DailyAdviceServer();
        server.go();

    }

}

 

DailyAdviceClient.java

import java.io.*;
import java.net.*;

public class DailyAdviceClient {
    public void go() {
        try {
            Socket s = new Socket("127.0.0.1", 4242);
            
            InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
            BufferedReader reader = new BufferedReader(streamReader);
            
            String advice = reader.readLine();
            System.out.println("Today you should: " + advice);
            reader.close();
            
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DailyAdviceClient client = new DailyAdviceClient();
        client.go();

    }

}

丑陋的输出:

技术分享

极简易版专家聊天程序--JAVA练手

标签:

原文地址:http://www.cnblogs.com/aguncn/p/4491912.html

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