search
HomeJavajavaTutorialDetailed explanation of Java's use of TCP to implement data transmission examples

Detailed explanation of Java's use of TCP to implement data transmission examples

Jun 17, 2017 pm 01:13 PM
javauseaccomplishdata transmissionDetailed explanation

这篇文章主要介绍了Java使用TCP实现数据传输实例详解的相关资料,需要的朋友可以参考下

Java使用TCP实现数据传输实例详解

TCP所提供服务的主要特点:

  1.面向连接的传输;
  2.端到端的通信;
  3.高可靠性,确保传输数据的正确性,不出现丢失或乱序;
  4.全双工方式传输;
  5.采用字节流方式,即以字节为单位传输字节序列;
  6.紧急数据传送功能。

TCP传输需要建立客户端和服务器端,即Socket和Server Socket , 建立连接后,通过Socket中的IO流进行数据的传输 。传输结束后关闭Socket。

客户端和服务器端是两个独立的应用程序。

以下是实现基本的TCP数据传输的Demo code:


package javase.day18; 
 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.net.ServerSocket; 
import java.net.Socket; 
 
public class TransTextDemo { 
  public static void main(String[] args) { 
  } 
 
} 
 
class TcpClient2{ 
  public static void main(String[] args) throws Exception{ 
    System.out.println("client start..."); 
    Socket s = new Socket("192.168.1.2",10005); 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 
    String sendDataStr=null; 
    while((sendDataStr=br.readLine())!=null){ 
      if(sendDataStr.equals("bye")){ 
        break; 
      } 
      bw.write(sendDataStr); 
      bw.newLine(); 
      bw.flush(); 
    } 
    bw.close(); 
  } 
} 
 
class TcpServer2{ 
  public static void main(String[] args) throws Exception{ 
    System.out.println("server start..."); 
    ServerSocket ss = new ServerSocket(10005); 
    Socket s = ss.accept(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); 
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 
    String receiveDataStr=null; 
    while((receiveDataStr=br.readLine())!=null){ 
      if(receiveDataStr.equals("bye")){ 
        break; 
      } 
      System.out.println("receive data:"+receiveDataStr); 
    } 
  } 
}

使用TCP实现文本文件上传的Demo code:


package javase.day18; 
 
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import java.net.ServerSocket; 
import java.net.Socket; 
 
public class UploadText { 
 
  public static void main(String[] args) { 
    // TODO Auto-generated method stub 
 
  } 
} 
 
 
 
class TextServer{ 
  public static void main(String[] args) throws Exception{ 
    System.out.println("Server start..."); 
    ServerSocket ss = new ServerSocket(10008); 
    Socket s = ss.accept(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); 
    PrintWriter out = new PrintWriter(new FileWriter("C:\\java_test\\server.txt"),true); 
    String line=null; 
    while((line=br.readLine())!=null){ 
      System.out.println(line); 
      out.println(line); 
    } 
     
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true); 
    pw.println("upload successful"); 
    pw.close(); 
    s.close(); 
    ss.close(); 
  } 
} 
 
 
class TextClient{ 
  public static void main(String[] args) throws Exception{ 
    System.out.println("Client start..."); 
    Socket clientSocket = new Socket("192.168.1.2",10008); 
    BufferedReader br = new BufferedReader(new FileReader("C:\\java_test\\SystemDemo.java")); 
    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true); 
    String line=null; 
    while((line=br.readLine())!=null){ 
      System.out.println(line); 
      out.println(line); 
    } 
    clientSocket.shutdownOutput(); 
    BufferedReader br2 = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
    String confirmMsgStr=br2.readLine(); 
    System.out.println(confirmMsgStr); 
    br2.close(); 
    clientSocket.close(); 
     
  } 
}

实现图片上传的Demo code:


package javase.day18; 
 
import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.net.ServerSocket; 
import java.net.Socket; 
 
public class UploadImage { 
 
  public static void main(String[] args) { 
 
  } 
 
} 
 
class ImageClient{ 
  public static void main(String[] args) throws Exception{ 
    Socket imageClientSocket = new Socket("192.168.1.2",10010); 
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\java_test\\client\\生活用品01.jpg")); 
    BufferedOutputStream bos = new BufferedOutputStream(imageClientSocket.getOutputStream()); 
    byte[] buf = new byte[1024*100]; 
    int len = 0 ; 
    while((len=bis.read(buf))!=-1){ 
      bos.write(buf,0,len); 
    } 
    imageClientSocket.shutdownOutput(); 
    BufferedInputStream bis2 = new BufferedInputStream(imageClientSocket.getInputStream()); 
    byte[] buf2 = new byte[1024]; 
    int len2 = 0 ; 
    while((len2=bis2.read(buf2))!=-1){ 
      System.out.println(new String(buf2,0,len2)); 
    } 
    bis.close(); 
    imageClientSocket.close(); 
     
  } 
} 
 
class ImageServer{ 
  public static void main(String[] args) throws Exception{ 
    ServerSocket ss = new ServerSocket(10010); 
    Socket s = ss.accept(); 
    BufferedInputStream bis = new BufferedInputStream(s.getInputStream()); 
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\java_test\\server\\生活用品01.jpg")); 
    byte[] buf = new byte[1024*100]; 
    int len = 0 ; 
    while((len=bis.read(buf))!=-1){ 
      bos.write(buf, 0, len); 
    } 
    BufferedOutputStream bos2 = new BufferedOutputStream(s.getOutputStream()); 
    bos2.write("upload successful".getBytes()); 
    bos2.close(); 
    s.close(); 
    ss.close(); 
  } 
}

The above is the detailed content of Detailed explanation of Java's use of TCP to implement data transmission examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.