线程下的udp和tcp局域网聊天
生活随笔
收集整理的這篇文章主要介紹了
线程下的udp和tcp局域网聊天
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
多線程,繼承Thread類,重寫run方法。
udp下的聊天。 兩方,每一方都可發,可收。
tcp下的聊天
package com.fun.test;import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.Scanner;public class MadeRun {/** @author echo lovely* * @Date 2020/1/7* * */public static void main(String[] args) throws Exception {Socket s = new Socket(InetAddress.getByName("127.0.0.1"), 10011);System.out.println("我是客戶端, pls answer me.");WriteThread wt = new WriteThread(s, new Scanner(System.in)); wt.start();ReadThread rt = new ReadThread(s);rt.start();} } // write class WriteThread extends Thread {Socket s = null;Scanner sc = null;public WriteThread() {}public WriteThread(Socket s, Scanner sc) {this.s = s;this.sc = sc;}public void run() {try { while (true) {OutputStream out = s.getOutputStream();byte[] b = sc.next().getBytes();out.write(b);} } catch (IOException e) {e.printStackTrace();}} }// read class ReadThread extends Thread {Socket s = null;public ReadThread() {}public ReadThread(Socket s) {this.s = s;}public void run() {try { while (true) { InputStream in = s.getInputStream();byte[] b = new byte[1024];int len = in.read(b);if (len != -1) {System.out.println(getName() + new String(b, 0, len));}} } catch (IOException e) {e.printStackTrace();}} } package com.fun.test;import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner;public class Test {public static void main(String[] args) throws IOException {ServerSocket ss = new ServerSocket(10011);System.out.println("服務端開啟啦");Socket s = ss.accept();// 10個線程池。int i = 0;for (i = 0; i < 10; i ++) {WriteThread wt = new WriteThread(s, new Scanner(System.in)); wt.start();ReadThread rt = new ReadThread(s);rt.start();} ss.close();} }tcp下的線程聊天的小bug,文字太長,不能全部收到。
好像多是廢話垃圾代碼。
總結
以上是生活随笔為你收集整理的线程下的udp和tcp局域网聊天的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 正则匹配 sql星号,正则表达
- 下一篇: IDEA配置JDK源码阅读环境