生活随笔
收集整理的這篇文章主要介紹了
(网络编程)TCP实现聊天
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
客戶端
通過socket連接服務器發送消息
import java
.io
.IOException
;
import java
.io
.OutputStream
;
import java
.net
.InetAddress
;
import java
.net
.Socket
;
import java
.net
.UnknownHostException
;public class TestClientDemo01 {public static void main(String
[] args
) {Socket socket
= null
;OutputStream os
= null
;try {InetAddress serverIp
= InetAddress
.getByName("127.0.0.1");int port
= 6666;socket
= new Socket(serverIp
,port
);os
= socket
.getOutputStream();os
.write("你好,服務器".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();}}}}
}
服務器
通過ServerSocket建立服務的端口等待用戶連接 accept接收用戶消息
import java
.io
.ByteArrayInputStream
;
import java
.io
.ByteArrayOutputStream
;
import java
.io
.IOException
;
import java
.io
.InputStream
;
import java
.net
.ServerSocket
;
import java
.net
.Socket
;public class TestServerDemo01 {public static void main(String
[] args
) {ServerSocket serverSocket
= null
;InputStream is
= null
;Socket socket
= null
;ByteArrayOutputStream baos
= null
;try {serverSocket
= new ServerSocket(6666);while (true) {System
.out
.println("等待客戶端消息.....");socket
= serverSocket
.accept();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 (IOException 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();}}}}
}
演示
運行服務器:
運行一次客戶端,發送消息給服務器
再次運行客戶端
總結
以上是生活随笔為你收集整理的(网络编程)TCP实现聊天的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。