多线程,继承Thread类,重写run方法。
udp下的聊天。 两方,每一方都可发,可收。
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;class Write extends Thread {DatagramSocket send = null;Scanner sc = null;int port = -1;public Write() {}public Write(DatagramSocket send, int port, Scanner sc) {this.send = send;this.port = port;this.sc = sc;}// 重写run方法public void run() {try {while (true) {//System.out.print("我:");byte[] b = sc.next().getBytes();DatagramPacket p = new DatagramPacket(b, b.length, InetAddress.getByName("127.0.01"), port);send.send(p);}} catch (Exception e) {e.printStackTrace();} finally {sc.close();send.close();}}
}class Read extends Thread {DatagramSocket socket = null;public Read() {}public Read(DatagramSocket receive) {this.socket = receive;}public void run() {while (true) { try {byte[] b = new byte[1024];DatagramPacket p = new DatagramPacket(b, b.length);socket.receive(p);byte[] data = p.getData();System.out.println("来自" + p.getPort() + "端口的消息: " + new String(data, 0, p.getLength()));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
}
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,文字太长,不能全部收到。
好像多是废话垃圾代码。