Java中怎么利用TCP實現(xiàn)一個在線聊天功能,相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),冀州企業(yè)網(wǎng)站建設(shè),冀州品牌網(wǎng)站建設(shè),網(wǎng)站定制,冀州網(wǎng)站建設(shè)報價,網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,冀州網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。客戶端的代碼:
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.創(chuàng)建SocketSocket tcpClientSocket=new Socket();//2.TCP要發(fā)送消息,必須先建立連接byte[] IPv4={127,0,0,1}; //連接到本機InetAddress serverAddress=InetAddress.getByAddress(IPv4);SocketAddress serverSocketAddress=new InetSocketAddress(serverAddress,7777);tcpClientSocket.connect(serverSocketAddress);//連接上了,(連接過程代碼比較長,但是沒有什么復(fù)雜的,只需要查文檔根據(jù)函數(shù)的構(gòu)造過程,一步步來寫就好了)while(true){ //寫個死循環(huán)來聊天String request=scanner.nextLine();//通過字節(jié)流寫入請求OutputStream os=tcpClientSocket.getOutputStream();//通過打印流打印和寫入PrintStream out=new PrintStream(os,true,"UTF-8");out.println(request);//通過字節(jié)流讀取響應(yīng)InputStream is=tcpClientSocket.getInputStream();BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8")); //通過readLine()來保證每次都能把一句完整的話讀完(\r\n是標(biāo)志);String response=reader.readLine();System.out.println(" "+response);}//tcpClientSocket.close();}}
服務(wù)器端的代碼:
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);//獲取字節(jié)流InputStream is=null;is=clientSocket.getInputStream();//字節(jié)流轉(zhuǎn)換為字符流InputStreamReader isReader=null;isReader=new InputStreamReader(is,"UTF-8");//獲取輸出字節(jié)流OutputStream os=clientSocket.getOutputStream();//獲取打印流PrintStream out=new PrintStream(os,true,"UTF-8");//獲取緩沖字符流BufferedReader reader=new BufferedReader(isReader);while(true){ //死循環(huán)聊天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{//監(jiān)聽連接ServerSocket tcpServerSocket=new ServerSocket(7777);//定義阻塞隊列BlockingQueue
看完上述內(nèi)容,你們掌握J(rèn)ava中怎么利用TCP實現(xiàn)一個在線聊天功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!