Java單線程程序?qū)崿F(xiàn)實現(xiàn)簡單聊天功能
信息發(fā)送
import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class May { public static void main(String[] args) { // 單線程程序 try { ServerSocket socket = new ServerSocket(2233);//端口號 Socket soc = socket.accept(); // 讀取信息 BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream())); PrintWriter out = new PrintWriter(soc.getOutputStream()); while (true) { // 發(fā)送 System.out.println("發(fā)送:"); String msg = new Scanner(System.in).nextLine(); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); out.println(String.format("[%s]:%s\r\n", "服務(wù)器", msg)); out.flush(); // 接收 System.out.println(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } } }
接收信息并回復(fù)
import java.io.*; import java.net.Socket; import java.util.Scanner; public class Max { public static void main(String[] args) { try { Socket s = new Socket("localhost",2233);//鏈接端口號 String sc = s.getInetAddress().getHostAddress();//獲取IP // 讀取信息 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out = new PrintWriter(s.getOutputStream()); while (true) { // 接收 System.out.println(br.readLine()); // 發(fā)送 System.out.println("發(fā)送:"); String msg = new Scanner(System.in).nextLine(); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); out.println(String.format("[%s]:%s\r\n", sc, msg)); out.flush(); } } catch (IOException e) { e.printStackTrace(); } } }
發(fā)送你好
接收你好并回復(fù)
[/code]
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Idea啟動SpringBoot程序報錯:Veb server failed to&nbs
這篇文章主要介紹了Idea啟動SpringBoot程序報錯:Veb server failed to start. Port 8082 was already in use;端口沖突的原理與解決方案,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下2024-10-10Spring?Boot中使用Swagger3.0.0版本構(gòu)建RESTful?APIs的方法
Swagger?是一個規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化?RESTful?風(fēng)格的?Web?服務(wù),這篇文章主要介紹了Spring?Boot中使用Swagger3.0.0版本構(gòu)建RESTful?APIs的方法,需要的朋友可以參考下2022-11-11Spring聲明式事務(wù)@Transactional注解實現(xiàn)元數(shù)據(jù)驅(qū)動的事務(wù)管理
這篇文章主要為大家介紹了Spring聲明式事務(wù)@Transactional注解實現(xiàn)元數(shù)據(jù)驅(qū)動的事務(wù)管理示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10springboot多模塊項目mvn打包遇到存在依賴但卻無法發(fā)現(xiàn)符號問題
在SpringBoot多模塊項目中,如果遇到依賴存在但無法發(fā)現(xiàn)符號的問題,常見原因可能是pom.xml配置問題,例如,如果某個模塊僅作為依賴而不是啟動工程,不應(yīng)在其pom中配置spring-boot-maven-plugin插件,因為這將影響jar包的生成方式2024-09-09關(guān)于Java集合框架Collection接口詳解
這篇文章主要介紹了關(guān)于Java集合框架Collection接口詳解,Collection接口是Java集合框架中的基礎(chǔ)接口,定義了一些基本的集合操作,包括添加元素、刪除元素、遍歷集合等,需要的朋友可以參考下2023-05-05Spring DATA JPA 中findAll 進行OrderBy方式
這篇文章主要介紹了Spring DATA JPA 中findAll 進行OrderBy方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11