点对点聊天
作者:互联网
1 package com.bjsxt; 2 3 import jdk.jfr.events.SocketReadEvent; 4 5 import java.io.BufferedReader; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.io.PrintWriter; 9 import java.net.ServerSocket; 10 import java.net.Socket; 11 import java.util.Scanner; 12 /* 发送消息线程*/ 13 class Send1 extends Thread{ 14 private Socket socket; 15 public Send1 (Socket socket){ 16 this.socket=socket; 17 } 18 @Override 19 public void run() { 20 this.sendMsg(); 21 } 22 /* 23 * 发送消息 24 * */ 25 private void sendMsg(){ 26 Scanner scanner = null; 27 PrintWriter pw =null; 28 try { 29 //创建键盘输入对象 30 scanner=new Scanner(System.in); 31 //创建向对方输出消息的流对象 32 pw=new PrintWriter(this.socket.getOutputStream()); 33 while (true){ 34 String msg=scanner.nextLine(); 35 pw.println(msg); 36 pw.flush(); 37 } 38 }catch (Exception e ){ 39 e.printStackTrace(); 40 }finally { 41 if (scanner!=null){ 42 scanner.close(); 43 } 44 if (pw!=null){ 45 pw.close(); 46 } 47 if (this.socket!=null){ 48 try { 49 this.socket.close(); 50 } catch (IOException e) { 51 e.printStackTrace(); 52 } 53 } 54 } 55 } 56 } 57 //接收消息的线程 58 class Receive1 extends Thread{ 59 private Socket socket; 60 public Receive1(Socket socket){ 61 this.socket=socket; 62 } 63 @Override 64 public void run() { 65 this.ReceiveMsg(); 66 } 67 //接收对象消息的方法 68 private void ReceiveMsg(){ 69 BufferedReader br = null; 70 try { 71 //创建用于接收对方发送消息的流对象 72 br=new BufferedReader(new InputStreamReader(this.socket.getInputStream())); 73 while (true){ 74 String msg=br.readLine(); 75 System.out.println("他说:"+msg); 76 } 77 78 }catch (Exception e){ 79 e.printStackTrace(); 80 }finally { 81 if (br!=null){ 82 try { 83 br.close(); 84 } catch (IOException e) { 85 e.printStackTrace(); 86 } 87 } 88 if (this.socket!=null){ 89 try { 90 this.socket.close(); 91 } catch (IOException e) { 92 e.printStackTrace(); 93 } 94 } 95 } 96 97 } 98 } 99 100 public class GoodTcp { 101 public static void main(String[] args) { 102 Scanner scanner =null; 103 ServerSocket serverSocket=null; 104 Socket socket=null; 105 try { 106 scanner=new Scanner(System.in); 107 System.out.println("请输入:server,<port>或者:<ip>,<port>"); 108 String str=scanner.nextLine(); 109 String[] arr = str.split(","); 110 if ("server".equals(arr[0])){ 111 //启动服务端 112 System.out.println("TCP Server Listen at"+arr[1]+"....."); 113 serverSocket =new ServerSocket(Integer.parseInt(arr[1])); 114 socket=serverSocket.accept(); 115 System.out.println("链接成功"); 116 }else{ 117 //启动客户端 118 socket=new Socket(arr[0],Integer.parseInt(arr[1])); 119 System.out.println("链接成功"); 120 } 121 //启动发送消息的线程 122 new Send1(socket).start(); 123 //启动接收消息的线程 124 new Receive1(socket).start(); 125 }catch (Exception e){ 126 e.printStackTrace(); 127 }finally { 128 if (serverSocket!=null){ 129 try { 130 serverSocket.close(); 131 } catch (IOException e) { 132 e.printStackTrace(); 133 } 134 } 135 } 136 } 137 }
标签:socket,点对点,聊天,import,new,null,Socket,scanner 来源: https://www.cnblogs.com/mashiyi/p/14751042.html