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();







目录
相关文章
|
7月前
|
Java
Java的Socket进行通信
下面是一个使用Java的Socket进行通信的简单示例
|
7月前
|
应用服务中间件
快速解决idea启动项目报错:Unable to open debugger port(127.0.0.1:58950):java.net.SocketException“socket closed
快速解决idea启动项目报错:Unable to open debugger port(127.0.0.1:58950):java.net.SocketException“socket closed
272 0
|
4月前
|
Java Android开发
如何在Java中创建Socket连接?
如何在Java中创建Socket连接?
69 0
|
2月前
|
Java
[Java]Socket套接字(网络编程入门)
[Java]Socket套接字(网络编程入门)
38 0
|
3月前
|
监控 应用服务中间件
idea debug模式启动Tomcat报错:Error running ‘tomcat8‘: java.net.SocketException “socket closed“
idea debug模式启动Tomcat报错:Error running ‘tomcat8‘: java.net.SocketException “socket closed“
|
3月前
|
Java
基于socket实现java Swing简易聊天室[附完整源码]
基于socket实现java Swing简易聊天室[附完整源码]
|
3月前
|
数据可视化 Java 关系型数据库
基于java Swing 框架使用socket技术开发的即时通讯系统【源码+数据库】
基于java Swing 框架使用socket技术开发的即时通讯系统【源码+数据库】
|
4月前
|
分布式计算 Linux Spark
【已解决】Caused by: java.net.SocketException: Connection reset by peer: socket write error
【已解决】Caused by: java.net.SocketException: Connection reset by peer: socket write error
70 0
|
4月前
|
网络协议 安全 Java
Java网络编程入门指南:TCP/IP协议与Socket通信
Java网络编程入门指南:TCP/IP协议与Socket通信
55 1
|
4月前
|
网络协议 Java
【零基础学Java】—Socket类(五十五)
【零基础学Java】—Socket类(五十五)
【零基础学Java】—Socket类(五十五)