Java網絡編程TCP實現聊天功能
網絡編程TCP實現聊天的前提還需要掌握IO流,話不多說,直接上代碼!
客戶端: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、要知道服務器的地址、端口號 InetAddress serverIP = InetAddress.getByName('127.0.0.1'); int port = 9999; //2、創建一個socket連接 socket = new Socket(serverIP, port); //3、發送消息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();} }} }}服務端:
package com.kuang.lesson02;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;//服務端public class TcpServerDemo01 { public static void main(String[] args) {ServerSocket serverSocket = null;Socket socket = null;InputStream is = null;ByteArrayOutputStream baos = null;try { //1、我得有一個地址 serverSocket = new ServerSocket(9999); while (true) {//2、等待客戶端連接過來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 { //關閉資源 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();} }} }}運行結果:
1、首先運行服務端,等待接收消息,可以發現服務端一直在運行
2、接著運行客戶端,發送消息,可以發現客戶端運行結束
3、返回服務端查看,可以發現服務端已經接收到了客戶端發送來的消息
4、由于是循環操作,所以只要客戶端發送消息來,服務端就能接收到,可以實現多次發送消息。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: