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();
    }

    }

  • 相关阅读:
    C++概念性总结
    友元函数
    C++指针概念
    Linux下多线程(clone()线程)
    Qt5模块化详细总结
    C++有符号与无符号之间的转换问题
    使用C++test工具做Qt代码静态分析
    QT函数带有外部链接但没有在头文件中声明(QT noreturn属性添加)
    Linux之Docker手动创建Docker容器
    我在思考一个很变态的社会趋向
  • 原文地址:https://www.cnblogs.com/angel512/p/5868150.html
Copyright © 2011-2022 走看看