簡單聊天Demo 使用tcp協議實現的簡單聊天功能(非常簡單的) 思想:使用2個線程,一個線程是用來接收消息的,另一個線程是用來發消息的。 客戶端Demo代碼: 伺服器端Demo代碼: 發送線程的Demo代碼: 接收線程的Demo代碼: ...
簡單聊天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 }