TCP協(xié)議是面向連接、保證高可靠性(數(shù)據(jù)無丟失、數(shù)據(jù)無失序、數(shù)據(jù)無錯誤、數(shù)據(jù)無重復(fù)到達(dá))傳輸層協(xié)議。
TCP通過三次握手建立連接,通訊完成時要拆除連接,由于TCP是面向連接的所以只能用于端到端的通訊。
本文主要介紹了java利用TCP實(shí)現(xiàn)簡單聊天的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧。
示例代碼
使用tcp協(xié)議實(shí)現(xiàn)的簡單聊天功能(非常簡單的)
思想:使用2個線程,一個線程是用來接收消息的,另一個線程是用來發(fā)消息的。
客戶端Demo代碼:
1
2
3
4
5
6
7
8
9
10
11
|
public class SendDemo { public static void main(String[] args) throws Exception{ Socket socket= new Socket(InetAddress.getLocalHost(), 8888 ); SendImpl sendImpl= new SendImpl(socket); //發(fā)送的線程 new Thread(sendImpl).start(); //接收的線程 ReciveImpl reciveImpl= new ReciveImpl(socket); new Thread(reciveImpl).start(); } } |
服務(wù)器端Demo代碼:
1
2
3
4
5
6
7
8
9
10
|
public class ServerDemo { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket( 8888 ); Socket socket=serverSocket.accept(); SendImpl sendImpl= new SendImpl(socket); new Thread(sendImpl).start(); ReciveImpl reciveImpl= new ReciveImpl(socket); new Thread(reciveImpl).start(); } } |
發(fā)送線程的Demo代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class SendImpl implements Runnable{ private Socket socket; public SendImpl(Socket socket) { this .socket=socket; // TODO Auto-generated constructor stub } @Override public void run() { Scanner scanner= new Scanner(System.in); while ( true ){ try { OutputStream outputStream = socket.getOutputStream(); String string= scanner.nextLine(); outputStream.write(string.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |
接收線程的Demo代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class ReciveImpl implements Runnable { private Socket socket; public ReciveImpl(Socket socket) { this .socket=socket; // TODO Auto-generated constructor stub } @Override public void run() { while ( true ){ try { InputStream inputStream = socket.getInputStream(); byte [] b= new byte [ 1024 ]; int len= inputStream.read(b); System.out.println( "收到消息:" + new String(b, 0 ,len)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對服務(wù)器之家的支持。
原文鏈接:http://www.cnblogs.com/xuzhaocai/archive/2017/12/24/8099681.html