您好,登录后才能下订单哦!
Java中怎么利用TCP实现一个在线聊天功能,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
客户端的代码:
package tcp.http;import java.io.*;import java.net.*;import java.util.Scanner;public class Client{public static void main(String[] args) throws IOException{Scanner scanner=new Scanner(System.in);//1.创建SocketSocket tcpClientSocket=new Socket();//2.TCP要发送消息,必须先建立连接byte[] IPv4={127,0,0,1}; //连接到本机InetAddress serverAddress=InetAddress.getByAddress(IPv4);SocketAddress serverSocketAddress=new InetSocketAddress(serverAddress,7777);tcpClientSocket.connect(serverSocketAddress);//连接上了,(连接过程代码比较长,但是没有什么复杂的,只需要查文档根据函数的构造过程,一步步来写就好了)while(true){ //写个死循环来聊天String request=scanner.nextLine();//通过字节流写入请求OutputStream os=tcpClientSocket.getOutputStream();//通过打印流打印和写入PrintStream out=new PrintStream(os,true,"UTF-8");out.println(request);//通过字节流读取响应InputStream is=tcpClientSocket.getInputStream();BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8")); //通过readLine()来保证每次都能把一句完整的话读完(\r\n是标志);String response=reader.readLine();System.out.println(" "+response);}//tcpClientSocket.close();}}
服务器端的代码:
package tcp.threads;import java.io.*;import java.net.*;import java.util.Scanner;import java.util.concurrent.*;public class Server{private static class TalkRunnable implements Runnable{ //一个个的工作线程private Socket clientSocket;TalkRunnable(Socket socket){this.clientSocket=socket;}@Overridepublic void run(){try{InetAddress clientAddress=clientSocket.getInetAddress();int clientPort=clientSocket.getPort();System.out.printf("ID为 %s:%d 的好友上线了%n",clientAddress.getHostAddress(),clientPort);//获取字节流InputStream is=null;is=clientSocket.getInputStream();//字节流转换为字符流InputStreamReader isReader=null;isReader=new InputStreamReader(is,"UTF-8");//获取输出字节流OutputStream os=clientSocket.getOutputStream();//获取打印流PrintStream out=new PrintStream(os,true,"UTF-8");//获取缓冲字符流BufferedReader reader=new BufferedReader(isReader);while(true){ //死循环聊天String line=reader.readLine();System.out.println(" 好友说:"+line);Scanner scanner=new Scanner(System.in);String response=scanner.nextLine();out.println(response);}}catch(IOException e){e.printStackTrace();}}}public static void main(String[] args) throws IOException{//监听连接ServerSocket tcpServerSocket=new ServerSocket(7777);//定义阻塞队列BlockingQueue<Runnable> queue=new LinkedBlockingQueue<>();//创建线程池ExecutorService pool=new ThreadPoolExecutor(100,100,0,TimeUnit.MILLISECONDS,queue);while(true){//TCP 要发送消息必须先建立连接Socket clientSocket=tcpServerSocket.accept();pool.execute(new TalkRunnable(clientSocket));//有一个客户端连接到服务器,就起一个线程来专门处理这个对话}}}
看完上述内容,你们掌握Java中怎么利用TCP实现一个在线聊天功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。