简单聊天Demo
使用tcp协议实现的简单聊天功能(非常简单的)
思想:使用2个线程,一个线程是用来接收消息的,另一个线程是用来发消息的。
客户端Demo代码:
1 public class SendDemo { 2 public static void main(String[] args) throws Exception{ 3 Socket socket= new Socket(InetAddress.getLocalHost(),8888); 4 SendImpl sendImpl= new SendImpl(socket); 5 //发送的线程 6 new Thread(sendImpl).start(); 7 //接收的线程 8 ReciveImpl reciveImpl=new ReciveImpl(socket); 9 new Thread(reciveImpl).start(); 10 } 11 12 }
服务器端Demo代码:
1 public class ServerDemo { 2 public static void main(String[] args) throws Exception { 3 ServerSocket serverSocket =new ServerSocket(8888); 4 Socket socket=serverSocket.accept(); 5 SendImpl sendImpl= new SendImpl(socket); 6 new Thread(sendImpl).start(); 7 ReciveImpl reciveImpl=new ReciveImpl(socket); 8 new Thread(reciveImpl).start(); 9 } 10 11 }
发送线程的Demo代码:
1 public class SendImpl implements Runnable{ 2 private Socket socket; 3 public SendImpl(Socket socket) { 4 this.socket=socket; 5 // TODO Auto-generated constructor stub 6 } 7 @Override 8 public void run() { 9 Scanner scanner=new Scanner(System.in); 10 while(true){ 11 try { 12 OutputStream outputStream = socket.getOutputStream(); 13 String string= scanner.nextLine(); 14 outputStream.write(string.getBytes()); 15 } catch (IOException e) { 16 // TODO Auto-generated catch block 17 e.printStackTrace(); 18 } 19 } 20 } 21 22 }
接收线程的Demo代码:
1 public class ReciveImpl implements Runnable { 2 private Socket socket; 3 public ReciveImpl(Socket socket) { 4 this.socket=socket; 5 // TODO Auto-generated constructor stub 6 } 7 @Override 8 public void run() { 9 while(true ){ 10 try { 11 InputStream inputStream = socket.getInputStream(); 12 byte[] b=new byte[1024]; 13 int len= inputStream.read(b); 14 System.out.println("收到消息:"+new String(b,0,len)); 15 16 } catch (IOException e) { 17 // TODO Auto-generated catch block 18 e.printStackTrace(); 19 } 20 } 21 } 22 23 }
时间: 2024-11-13 08:57:27