Java網(wǎng)絡(luò)編程TCP實(shí)現(xiàn)聊天功能
網(wǎng)絡(luò)編程TCP實(shí)現(xiàn)聊天的前提還需要掌握IO流,話不多說(shuō),直接上代碼!
客戶端:package com.kuang.lesson02;import java.io.IOException;import java.io.OutputStream;import java.net.InetAddress;import java.net.Socket;//客戶端public class TcpClientDemo01 { public static void main(String[] args) {Socket socket = null;OutputStream os = null;try { //1、要知道服務(wù)器的地址、端口號(hào) InetAddress serverIP = InetAddress.getByName('127.0.0.1'); int port = 9999; //2、創(chuàng)建一個(gè)socket連接 socket = new Socket(serverIP, port); //3、發(fā)送消息IO流 os = socket.getOutputStream(); os.write('你好,Java'.getBytes());} catch (Exception e) { e.printStackTrace();} finally { if (os != null) {try { os.close();} catch (IOException e) { e.printStackTrace();} } if (socket != null) {try { socket.close();} catch (IOException e) { e.printStackTrace();} }} }}服務(wù)端:
package com.kuang.lesson02;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;//服務(wù)端public class TcpServerDemo01 { public static void main(String[] args) {ServerSocket serverSocket = null;Socket socket = null;InputStream is = null;ByteArrayOutputStream baos = null;try { //1、我得有一個(gè)地址 serverSocket = new ServerSocket(9999); while (true) {//2、等待客戶端連接過(guò)來(lái)socket = serverSocket.accept();//3、讀取客戶端的消息is = socket.getInputStream();//管道流baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len;while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len);}System.out.println(baos.toString()); }} catch (Exception e) { e.printStackTrace();} finally { //關(guān)閉資源 if (baos != null) {try { baos.close();} catch (IOException e) { e.printStackTrace();} } if (is != null) {try { is.close();} catch (IOException e) { e.printStackTrace();} } if (socket != null) {try { socket.close();} catch (IOException e) { e.printStackTrace();} } if (serverSocket != null) {try { serverSocket.close();} catch (IOException e) { e.printStackTrace();} }} }}運(yùn)行結(jié)果:
1、首先運(yùn)行服務(wù)端,等待接收消息,可以發(fā)現(xiàn)服務(wù)端一直在運(yùn)行

2、接著運(yùn)行客戶端,發(fā)送消息,可以發(fā)現(xiàn)客戶端運(yùn)行結(jié)束

3、返回服務(wù)端查看,可以發(fā)現(xiàn)服務(wù)端已經(jīng)接收到了客戶端發(fā)送來(lái)的消息

4、由于是循環(huán)操作,所以只要客戶端發(fā)送消息來(lái),服務(wù)端就能接收到,可以實(shí)現(xiàn)多次發(fā)送消息。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. idea刪除項(xiàng)目的操作方法2. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法3. IntelliJ IDEA恢復(fù)刪除文件的方法4. 使用Maven 搭建 Spring MVC 本地部署Tomcat的詳細(xì)教程5. IntelliJ IDEA導(dǎo)入jar包的方法6. IntelliJ IDEA設(shè)置自動(dòng)提示功能快捷鍵的方法7. idea重置默認(rèn)配置的方法步驟8. Docker 部署 Prometheus的安裝詳細(xì)教程9. idea導(dǎo)入maven項(xiàng)目的方法10. IntelliJ IDEA調(diào)整字體大小的方法

網(wǎng)公網(wǎng)安備