Java使用TCP實現(xiàn)在線聊天的示例代碼
更新時間:2020年01月03日 15:15:36 作者:小矮多
這篇文章主要介紹了Java使用TCP實現(xiàn)在線聊天的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
客戶端的代碼:
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)建Socket
Socket 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);//連接上了,(連接過程代碼比較長,但是沒有什么復雜的,只需要查文檔根據(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é)流讀取響應
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;
}
@Override
public 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<Runnable> queue=new LinkedBlockingQueue<>();
//創(chuàng)建線程池
ExecutorService pool=new ThreadPoolExecutor(100,100,0,TimeUnit.MILLISECONDS,queue);
while(true){
//TCP 要發(fā)送消息必須先建立連接
Socket clientSocket=tcpServerSocket.accept();
pool.execute(new TalkRunnable(clientSocket));//有一個客戶端連接到服務器,就起一個線程來專門處理這個對話
}
}
}
運行結(jié)果:

為什么要使用多線程?
因為單線程會發(fā)生阻塞,聊天就進行不下去了。。。
又是自己和自己聊天的一天= =,最近好迷TCP和UDP,歡迎各位大佬批評指正呀,一起交流呀!!! 啦啦啦
對比這個聊天程序和上一篇用UDP寫的聊天程序可以更好的體會TCP和UDP的區(qū)別。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java中的HashMap為什么會產(chǎn)生死循環(huán)
這篇文章主要介紹了Java中的HashMap為什么會產(chǎn)生死循環(huán),HashMap?死循環(huán)是一個比較常見、比較經(jīng)典的問題,下面文章我們就來徹底理解死循環(huán)的原因。需要的小伙伴可以參考一下2022-05-05
IntelliJ IDEA安裝scala插件并創(chuàng)建scala工程的步驟詳細教程
這篇文章主要介紹了IntelliJ IDEA安裝scala插件并創(chuàng)建scala工程的步驟,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07

