Java Networking: Socket

简介: Java Networking 1Java Networking2Java Networking: Socket3Java Networking: ServerSocket4Java Networking: UDP DatagramSocket5Java...


Java Networking 

1 Java Networking
2 Java Networking: Socket
3 Java Networking: ServerSocket
4 Java Networking: UDP DatagramSocket
5 Java Networking: URL + URLConnection
6 Java Networking: JarURLConnection
7 Java Networking: InetAddress
8 Java Networking: Protocol Design

Java Networking: Socket

 
By Jakob Jenkov
 Connect with me: 
Rate article:
<iframe frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1416446000690" name="I0_1416446000690" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&amp;origin=http%3A%2F%2Ftutorials.jenkov.com&amp;url=http%3A%2F%2Ftutorials.jenkov.com%2Fjava-networking%2Fsockets.html&amp;gsrc=3p&amp;ic=1&amp;jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.zh_CN.0KI2lcOUxJ0.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPnLWTRWXjQ3yHtGTFSsUVyRcOV5g#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&amp;id=I0_1416446000690&amp;parent=http%3A%2F%2Ftutorials.jenkov.com&amp;pfname=&amp;rpctoken=31463063" data-gapiattached="true" style="position: absolute; top: -10000px; width: 450px; margin: 0px; border-style: none;"></iframe>
Share article:
<iframe frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I1_1416446000694" name="I1_1416446000694" src="https://apis.google.com/se/0/_/+1/sharebutton?plusShare=true&amp;usegapi=1&amp;action=share&amp;height=24&amp;annotation=none&amp;origin=http%3A%2F%2Ftutorials.jenkov.com&amp;url=http%3A%2F%2Ftutorials.jenkov.com%2Fjava-networking%2Fsockets.html&amp;gsrc=3p&amp;ic=1&amp;jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.zh_CN.0KI2lcOUxJ0.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPnLWTRWXjQ3yHtGTFSsUVyRcOV5g#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh%2Conload&amp;id=I1_1416446000694&amp;parent=http%3A%2F%2Ftutorials.jenkov.com&amp;pfname=&amp;rpctoken=22420384" data-gapiattached="true" style="position: absolute; top: -10000px; width: 450px; margin: 0px; border-style: none;"></iframe>

In order to connect to a server over the internet (via TCP/IP) in Java, you need to create a java.net.Socket and connect it to the server. Alternatively you can use a Java NIO SocketChannel, in case you prefer to use Java NIO.

Creating a Socket

This code example connects to the server with IP address 78.46.84.171 on port 80. That server happens to be my web server (www.jenkov.com), and port 80 is the web servers port.

Socket socket = new Socket("78.46.84.171", 80);

You can also use a domain name instead of an IP address, like this:

Socket socket = new Socket("jenkov.com", 80);

Writing to a Socket

To write to a Java Socket you must obtain its OutputStream. Here is how that is done:

Socket socket = new Socket("jenkov.com", 80);
OutputStream out = socket.getOutputStream();

out.write("some data".getBytes());
out.flush();
out.close();

socket.close();

That's how simple it is!

Don't forget to call flush() when you really, really want the data sent across the internet to the server. The underlying TCP/IP implementation in your OS may buffer the data and send it in larger chunks to fit with with the size of TCP/IP packets.

Reading from a Socket

To read from a Java Socket you will need to obtains its InputStream. Here is how that is done:

Socket socket = new Socket("jenkov.com", 80);
InputStream in = socket.getInputStream();

int data = in.read();
//... read more data...

in.close();
socket.close();

Pretty simple, right?

Keep in mind that you cannot always just read from the Socket's InputStream until it returns -1, as you can when reading a file. The reason is that -1 is only returned when the server closes the connection. But a server may not always close the connection. Perhaps you want to send multiple requests over the same connection. In that case it would be pretty stupid to close the connection.

Instead you must know how many bytes to read from the Socket's InputStream. This can be done by either the server telling how many bytes it is sending, or by looking for a special end-of-data character.

Closing a Socket

When you are done using a Java Socket you must close it to close the connection to the server. This is done by calling the Socket.close() method, like this:

Socket socket = new Socket("jenkov.com", 80);

socket.close();






目录
相关文章
|
23天前
|
Java 流计算
Flink-03 Flink Java 3分钟上手 Stream 给 Flink-02 DataStreamSource Socket写一个测试的工具!
Flink-03 Flink Java 3分钟上手 Stream 给 Flink-02 DataStreamSource Socket写一个测试的工具!
34 1
Flink-03 Flink Java 3分钟上手 Stream 给 Flink-02 DataStreamSource Socket写一个测试的工具!
|
6天前
|
Java
[Java]Socket套接字(网络编程入门)
本文介绍了基于Java Socket实现的一对一和多对多聊天模式。一对一模式通过Server和Client类实现简单的消息收发;多对多模式则通过Server类维护客户端集合,并使用多线程实现实时消息广播。文章旨在帮助读者理解Socket的基本原理和应用。
12 1
|
27天前
|
网络协议 安全 Java
Java Socket原理
Java Socket原理是指在Java中通过Socket实现的网络通信的基础理论与机制。Socket是网络中不同设备间通信的一种标准方式,它允许应用程序之间通过TCP/IP等协议进行数据交换。在Java中,利用Socket编程可以方便地创建客户端与服务器端应用,实现跨网络的数据传输功能,是互联网软件开发中的重要技术之一。它支持多种通信模式,如可靠的流式套接字(TCP)和数据报式套接字(UDP)。
|
4月前
|
Java
如何在Java中实现多线程的Socket服务器?
在Java中,多线程Socket服务器能同时处理多个客户端连接以提升并发性能。示例代码展示了如何创建此类服务器:监听指定端口,并为每个新连接启动一个`ClientHandler`线程进行通信处理。使用线程池管理这些线程,提高了效率。`ClientHandler`读取客户端消息并响应,支持简单的文本交互,如发送欢迎信息及处理退出命令。
|
4月前
|
网络协议 安全 Java
Java中的网络编程:Socket编程详解
Java中的网络编程:Socket编程详解
|
4月前
|
Java API 开发者
Java中的Socket编程与应用
Java中的Socket编程与应用
|
4月前
|
网络协议 安全 Java
Java中的网络编程:Socket编程详解
Java中的网络编程:Socket编程详解
|
4月前
|
Java API 开发者
Java中的Socket编程与应用
Java中的Socket编程与应用
|
4月前
|
网络协议 Java
如何在Java中使用Socket编程实现TCP连接?
在Java中,通过Socket编程实现TCP连接非常常见。以下演示了基本的TCP通信流程,可根据具体需求进行扩展。
229 0
|
4月前
|
Java 数据格式
Java面试题:简述Java Socket编程的基本流程,包括客户端和服务器的创建与通信。
Java面试题:简述Java Socket编程的基本流程,包括客户端和服务器的创建与通信。
69 0