Home Java javaTutorial Network programming in Java

Network programming in Java

Jun 08, 2023 pm 04:59 PM
java network programming Network socket programming java socket communication

With the rapid development of the Internet, network programming has become more and more important. As a popular programming language, Java naturally has strong network programming capabilities. This article will provide a brief introduction to network programming in Java.

  1. Basics

In Java, network programming requires the use of two important classes: Socket and ServerSocket. The Socket class is used to establish client-side connections, while ServerSocket is used to create server-side connections. Socket objects are created by specifying the IP address and port number, while ServerSocket is created by specifying the local port number.

  1. Network transmission protocol

When doing network programming, you need to understand some basic network transmission protocols, such as TCP/IP, UDP and HTTP. TCP/IP and UDP are the two most commonly used protocols. TCP/IP is a connection-oriented protocol that provides reliable data transmission, while UDP is a connectionless protocol that provides faster data transmission. The HTTP protocol is an offline request and response protocol, which is widely used in communication between web servers and browsers.

  1. Write a network program based on TCP/IP protocol

The following is an example of a simple client/server program:

Client:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import java.net.*;

import java.io.*;

public class Client {

   public static void main(String [] args) {

      String serverName = args[0];

      int port = Integer.parseInt(args[1]);

      try {

         System.out.println("连接到主机:" + serverName + " ,端口号:" + port);

         Socket client = new Socket(serverName, port);

         System.out.println("远程主机地址:" + client.getRemoteSocketAddress());

         OutputStream outToServer = client.getOutputStream();

         DataOutputStream out = new DataOutputStream(outToServer);

         out.writeUTF("Hello from " + client.getLocalSocketAddress());

         InputStream inFromServer = client.getInputStream();

         DataInputStream in = new DataInputStream(inFromServer);

         System.out.println("服务器响应: " + in.readUTF());

         client.close();

      } catch (IOException e) {

         e.printStackTrace();

      }

   }

}

Copy after login

Server side:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

import java.net.*;

import java.io.*;

public class Server extends Thread {

   private ServerSocket serverSocket;

    

   public Server(int port) throws IOException {

      serverSocket = new ServerSocket(port);

      serverSocket.setSoTimeout(10000);

   }

 

   public void run() {

      while(true) {

         try {

            System.out.println("等待客户端连接,端口号为:" + serverSocket.getLocalPort() + "...");

            Socket server = serverSocket.accept();

            System.out.println("远程主机地址:" + server.getRemoteSocketAddress());

            DataInputStream in = new DataInputStream(server.getInputStream());

            System.out.println(in.readUTF());

            DataOutputStream out = new DataOutputStream(server.getOutputStream());

            out.writeUTF("感谢连接我:" + server.getLocalSocketAddress() + "

Goodbye!");

            server.close();

         } catch (SocketTimeoutException s) {

            System.out.println("Socket timed out!");

            break;

         } catch (IOException e) {

            e.printStackTrace();

            break;

         }

      }

   }

    

   public static void main(String [] args) {

      int port = Integer.parseInt(args[0]);

      try {

         Thread t = new Server(port);

         t.start();

      } catch (IOException e) {

         e.printStackTrace();

      }

   }

}

Copy after login

This program demonstrates simple communication between client and server. When the client runs, it sends a string to the server, and the server responds with the string.

  1. Summary

Network programming in Java can be performed using protocols such as TCP/IP and UDP. When writing network programs, you need to use the Socket class and ServerSocket class.

The above is just the introductory part of network programming in Java. There are many things that need to be understood in depth about network programming, such as the sending and receiving of data packets, multi-threaded network programming, and accessing web servers through HTTP.

The above is the detailed content of Network programming in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The Terminator of Java Network Programming: Solve Your Networking Problems Once and for All The Terminator of Java Network Programming: Solve Your Networking Problems Once and for All Mar 18, 2024 am 10:10 AM

Java is a powerful programming language ideal for developing web applications. It provides a comprehensive set of class libraries and tools that enable developers to easily build reliable and efficient web applications. However, network programming can be a complex process, and developers often encounter various problems. This article aims to delve into common problems in Java network programming and provide comprehensive solutions. Network connection issues Unable to connect to the server: Check your firewall settings to make sure the Java application is allowed to access the network. Verify that the server is running and listening for incoming connections. Connection timeout: Increase the connection timeout to accommodate slow or unstable network connections. Consider using non-blocking IO or asynchronous programming to improve connection responsiveness. Socket is different

Introduction to distributed applications in Java language Introduction to distributed applications in Java language Jun 09, 2023 pm 07:25 PM

The Java language is a typical object-oriented programming language, and it has become the first choice language for many software engineers when developing distributed applications. In distributed applications, different systems and components need to work together, and they also need to solve a series of problems in a distributed environment, such as communication, data synchronization, load balancing, and fault recovery. Therefore, in the development of Java distributed applications, you need to master a series of technologies, and you need to understand the advantages, disadvantages and applicable scenarios of different technologies. Some basics for developing distributed applications in Java

Network programming in Java Network programming in Java Jun 08, 2023 pm 04:59 PM

With the rapid development of the Internet, network programming has become more and more important. As a popular programming language, Java naturally has strong network programming capabilities. This article will provide a brief introduction to network programming in Java. Basics In Java, network programming requires the use of two important classes: Socket and ServerSocket. The Socket class is used to establish client-side connections, while ServerSocket is used to create server-side connections. The Socket object passes the specified IP address

How to use network programming functions in Java for network communication How to use network programming functions in Java for network communication Oct 20, 2023 pm 05:31 PM

How to use network programming functions in Java for network communication In today's information age, network communication is a very important part. As a cross-platform programming language, Java provides powerful network programming functions, allowing developers to easily implement network communication functions in programs. This article will introduce how to use network programming functions in Java for network communication and provide specific code examples. Create a server: To implement network communication, you first need a server that can receive and process client requests. in Java

Network programming in Java: explanation of key technologies Network programming in Java: explanation of key technologies Jun 16, 2023 am 09:34 AM

With the rapid development of the Internet era, more and more applications require communication through the network. As a development language, Java also has powerful applications and support in the field of network programming. This article will focus on explaining the key technologies of network programming in Java. 1. Socket programming Socket refers to the communication endpoint between two programs. In Java, Socket programming is the most basic part of network programming. Using Socket, we can establish connections between different computers and transfer data. Java

Proficient in Java network programming: Project practice for creating efficient communication functions Proficient in Java network programming: Project practice for creating efficient communication functions Nov 20, 2023 am 11:30 AM

In today's information age, network communication has become an indispensable part of people's lives and work. As a Java developer, if you want to succeed in the field of network programming, it is crucial to master Java network programming. As a widely used programming language, Java provides developers with a wealth of network programming tools and frameworks, such as Socket, Netty, ApacheHttpClient, etc. Therefore, being proficient in Java network programming can not only help developers build efficient and stable networks

Java network connection performance optimization strategies Java network connection performance optimization strategies Jun 30, 2023 pm 05:04 PM

How to optimize network connection creation and destruction performance in Java development Introduction: In modern software development, network connections have become an indispensable part. Especially in Java development, the creation and destruction performance of network connections is directly related to the overall performance of the software system. Therefore, optimizing the creation and destruction performance of network connections is a skill that must be mastered in Java development. This article will introduce some methods and techniques for optimizing network connection performance. 1. Use connection pooling technology. Connection pooling is a common and effective way to optimize network connection performance.

How to deal with network connection timeout issues in Java development How to deal with network connection timeout issues in Java development Jun 29, 2023 am 11:12 AM

How to deal with network connection timeout issues in Java development Summary: In modern network application development, network connection timeout has become a common problem. This article will introduce how to deal with network connection timeout issues in Java development, including setting the connection timeout, using threads to handle timeouts, and using third-party libraries. I hope to provide some help and guidance to the majority of Java developers in solving network connection timeout problems. Keywords: Java development, network connection timeout, connection timeout, thread processing, introduction to third-party libraries With the Internet

See all articles