Java Socket Programming

本文介绍了Java Socket编程的基本概念,包括面向连接和无连接的编程方式,并详细讲解了Socket和ServerSocket类的使用方法及关键API。通过一个简单的客户端发送文本到服务器的例子,帮助读者理解Java Socket编程的基础。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java Socket programming is used for communication between the applications running on different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:

IP Address of Server, and
Port number.

Socket class

A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket.

Important methods

Method Description
1) public InputStream getInputStream()
returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.
3) public synchronized void close() closes this socket

ServerSocket class

The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients.

Important methods

Method Description
1) public Socket accept()returns the socket and establish a connection between server and client.
2) public synchronized void close() closes the server socket.

Example of Java Socket Programming

Let’s see a simple of java socket programming in which client sends a text and server receives it.

这里写代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值