溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

javaTcp通信客戶端與服務器端實例代碼

發(fā)布時間:2021-09-18 03:39:07 來源:億速云 閱讀:114 作者:chen 欄目:編程語言

本篇內(nèi)容介紹了“javaTcp通信客戶端與服務器端實例代碼”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

本文實例講述了java Tcp通信客戶端與服務器端。分享給大家供大家參考,具體如下:

由服務器端發(fā)送數(shù)據(jù)

服務器端:

import java.io.*;import java.net.*;public class TestSocket { public static void main(String[] args) { try {  ServerSocket ss = new ServerSocket(8888);  while(true) {  Socket s = ss.accept();  OutputStream os = s.getOutputStream();  DataOutputStream dos = new DataOutputStream(os);  dos.writeUTF("hello" + s.getInetAddress() + "port" + s.getPort() + "beybye");  dos.close();//  os.flush();  os.close();//  s.close();  } } catch (IOException e) {  e.printStackTrace();  System.out.println("there is a wrong"); } }}

用戶端:

import java.io.*;import java.net.*;public class TestClient { public static void main(String[] args){ try {  Socket s = new Socket("127.0.0.1",8888);  DataInputStream dis = new DataInputStream(s.getInputStream());  System.out.println(dis.readUTF());   s.close();  dis.close(); } catch (Exception e) {  e.printStackTrace(); } }}

無論是客戶端還是服務器端都可以收發(fā)數(shù)據(jù)。

交互型

用戶端

import java.io.*;import java.net.*;public class TestClient2 { public static void main(String[] args){ try {  Socket s = new Socket("127.0.0.1",8886);  DataOutputStream dos = new DataOutputStream(s.getOutputStream());  DataInputStream dis = new DataInputStream(s.getInputStream());  System.out.println(dis.readUTF());   dos.writeUTF("hey");  String str = null;  if((str = dis.readUTF()) != null) {  System.out.println(str);  }  s.close();  dis.close();  dos.close(); } catch (Exception e) {  e.printStackTrace(); } }}

服務器端:

public class TestServer2 { public static void main(String[] args) { InputStream in = null; OutputStream out = null; try {  ServerSocket ss = new ServerSocket(8886);  while(true) {  Socket s = ss.accept();  in = s.getInputStream();  out = s.getOutputStream();  DataOutputStream dos = new DataOutputStream(s.getOutputStream());  DataInputStream dis = new DataInputStream(s.getInputStream());  String str = null;  if((str = dis.readUTF() )!= null) {   System.out.println(str);   System.out.println("form " + s.getInetAddress());   System.out.println("port " + s.getPort());//   dos.writeUTF("hello" + s.getInetAddress() + "port" + s.getPort() + "beybye");  }  dos.writeUTF("hi hello");  dis.close();  dos.close();  s.close();  } } catch (IOException e) {  e.printStackTrace();  System.out.println("there is a wrong"); } }}

“javaTcp通信客戶端與服務器端實例代碼”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識可以關注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI