TCP
TCP協議是面向連接、保證高可靠性(數據無丟失、數據無失序、數據無錯誤、數據無重復到達)傳輸層協議。
TCP通過三次握手建立連接,通訊完成時要拆除連接,由于TCP是面向連接的所以只能用于端到端的通訊。
本文主要介紹了javascript/39725.html">java/67933.html">java利用TCP實現簡單聊天的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
示例代碼
使用tcp協議實現的簡單聊天功能(非常簡單的)
思想:使用2個線程,一個線程是用來接收消息的,另一個線程是用來發消息的。
客戶端Demo代碼:
public class SendDemo { public static void main(String[] args) throws Exception{ Socket socket= new Socket(InetAddress.getLocalHost(),8888); SendImpl sendImpl= new SendImpl(socket); //發送的線程 new Thread(sendImpl).start(); //接收的線程 ReciveImpl reciveImpl=new ReciveImpl(socket); new Thread(reciveImpl).start(); }}
服務器端Demo代碼:
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(); }}
發送線程的Demo代碼:
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代碼:
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(); } } }}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答
圖片精選