亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

java學(xué)習(xí)之利用TCP實(shí)現(xiàn)的簡單聊天示例代碼

 更新時(shí)間:2017年12月25日 11:41:26   作者:猿上生活  
這篇文章主要給大家介紹了關(guān)于java學(xué)習(xí)筆記之利用TCP實(shí)現(xiàn)的簡單聊天的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。

TCP

TCP協(xié)議是面向連接、保證高可靠性(數(shù)據(jù)無丟失、數(shù)據(jù)無失序、數(shù)據(jù)無錯(cuò)誤、數(shù)據(jù)無重復(fù)到達(dá))傳輸層協(xié)議。

TCP通過三次握手建立連接,通訊完成時(shí)要拆除連接,由于TCP是面向連接的所以只能用于端到端的通訊。

本文主要介紹了java利用TCP實(shí)現(xiàn)簡單聊天的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧。

示例代碼

使用tcp協(xié)議實(shí)現(xiàn)的簡單聊天功能(非常簡單的)

思想:使用2個(gè)線程,一個(gè)線程是用來接收消息的,另一個(gè)線程是用來發(fā)消息的。

客戶端Demo代碼:

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代碼:

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代碼:

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();
  }
 }
 }
}

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論