A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 徐壹 于 2018-12-20 08:44 编辑

局域网「点对点」聊天工具客户端:
[Java] 纯文本查看 复制代码
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
​
/**
* @Author:hr947x
* @Date:2018/12/19 11:44
* @version:1.0
*/
public class Client {
   public static void main(String[] args) throws IOException {
​
       Scanner sc = new Scanner(System.in);
       System.out.println("请输入你的名字:");
       String name = s.nextLine();
       System.out.println("等待连接服务器...");
​
       Socket s = new Socket("127.0.0.1", 13579);
       OutputStream ops = s.getOutputStream();
       String getMessage = "";
​
       ops.write(name + "连接成功!".getBytes());
​
       // 接收消息线程
       new Thread(()->{try {
           while (true) {
               InputStream ips = s.getInputStream();
               byte[] bytes = new byte[1024];
               int len = -1;
               len = ips.read(bytes);
               System.out.println(new String(bytes, 0, len));
          }
      } catch (IOException e) {
           e.printStackTrace();
      }}).start();
​
       // 死循环发送消息
       while (true) {
           ops.write((name + ":" + sc.nextLine()).getBytes());
      }
  }
}



服务器端:

[Java] 纯文本查看 复制代码
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
​
/**
* @Author:hr947x
* @Date:2018/12/19 11:44
* @version:1.0
*/
public class Server {
   public static void main(String[] args) throws IOException {
​
       Scanner sc = new Scanner(System.in);
       System.out.println("请输入你的名字:");
       String name = s.nextLine();
       System.out.println("等待客户端连接...");
​
       ServerSocket ss = new ServerSocket(13579);
       Socket s = ss.accept();
       OutputStream os = s.getOutputStream();
​
       os.write(name + "连接成功!".getBytes());
​
       // 接收消息线程
       new Thread(() -> {
           try {
               while (true) {
                   InputStream is = s.getInputStream();
                   byte[] bytes = new byte[1024];
                   int len = -1;
                   len = is.read(bytes);
                   System.out.println(new String(bytes, 0, len));
              }
          } catch (IOException e) {
               e.printStackTrace();
          }
      }).start();
​
       // 死循环发送消息
       while (true) {
           os.write((name + ":" + sc.nextLine()).getBytes());
      }
​
  }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马