欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实现TCP的 客户端和服务器端的 即时聊天通信

程序员文章站 2022-07-01 08:02:12
...
package com.gg.talk.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ServerDemo {
public static void main(String[] args) throws Exception {
	ServerSocket server=new ServerSocket(8888);
    Scanner scanner=new Scanner(System.in);
    while(true) {
    	Socket socket=server.accept();
    	
    new Thread(new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(true) {
				OutputStream os;
				try {
					os = socket.getOutputStream();
					String msg=scanner.nextLine();
					os.write(msg.getBytes());
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	}).start();
    
    //读线程
    new Thread(new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(true) {
				try {
					InputStream is=socket.getInputStream();
					if(is!=null) {
						byte[] b=new byte[1024];
						int len=is.read(b);
						if(len!=-1) {
							String res=new String(b,0,len);
							System.out.println(res);
						}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	}).start();
    }
}
}

package com.gg.talk.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ClientDemo {
     public static void main(String[] args) throws Exception, Exception {
		 Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),8888);
    
           System.out.println("成功连接服务器,开始聊天。。。。");
           Scanner scanner=new Scanner(System.in);
           new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true) {
					OutputStream os;
					try {
						os = socket.getOutputStream();
						String msg=scanner.nextLine();
						os.write(msg.getBytes());
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
		}).start();
           
           //读线程
           new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true) {
					try {
						InputStream is=socket.getInputStream();
						if(is!=null) {
							byte[] b=new byte[1024];
							int len=is.read(b);
							if(len!=-1) {
								String res=new String(b,0,len);
								System.out.println(res);
							}
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
		}).start();
           
     }
     
	
}