zoukankan      html  css  js  c++  java
  • 简单的聊天时范例(客户端)

    package j2se.core.net.chat;


    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.ServerSocket;
    import java.net.Socket;

    /**
    * 简单的聊天室范例(服务器端)
    */
    public class Server {

    public static void main(String[] args) throws IOException {
    ServerSocket server = new ServerSocket(8888);
    while (true) {
    final Socket socket = server.accept();
    Thread t1 = new Thread() {
    @Override
    public void run() {
    DataInputStream input;
    try {
    input = new DataInputStream(socket.getInputStream());
    while (true) {
    String s = input.readUTF();
    System.out.println("客户端说:" + s);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    };
    t1.start();

    Thread t2 = new Thread() {
    @Override
    public void run() {
    BufferedReader br = new BufferedReader(
    new InputStreamReader(System.in));
    try {
    DataOutputStream out = new DataOutputStream(
    socket.getOutputStream());
    while (true) {
    String s = br.readLine();
    out.writeUTF(s);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    };
    t2.start();
    }
    }

    }

    package j2se.core.net.chat;

    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Socket;
    import java.net.UnknownHostException;

    /**
    * 简单的聊天时范例(客户端)
    */
    public class Client {

    public static void main(String[] args) throws UnknownHostException, IOException {
    final Socket s = new Socket("127.0.0.1", 8888);
    Thread t1 = new Thread() {
    @Override
    public void run() {
    DataInputStream input;
    try {
    input = new DataInputStream(s.getInputStream());
    while (true) {
    String s = input.readUTF();
    System.out.println("服务端说:" + s);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    };
    t1.start();

    Thread t2 = new Thread() {
    @Override
    public void run() {
    BufferedReader br = new BufferedReader(
    new InputStreamReader(System.in));
    try {
    DataOutputStream out = new DataOutputStream(s.getOutputStream());
    while (true) {
    String s = br.readLine();
    out.writeUTF(s);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    };
    t2.start();
    }

    }

  • 相关阅读:
    【转】JVM 堆内存设置原理
    【转】Java八种基本数据类型的比较及其相互转化
    8月12日
    并发与竞争
    高通gpio配置输出
    创建一个字符设备的基本流程
    4月2号 字符设备驱动实验
    3.30学习遇到卡死点
    断言函数的用法
    12.02 下午
  • 原文地址:https://www.cnblogs.com/angel512/p/5868150.html
Copyright © 2011-2022 走看看