1.服务端的实现
1.1.设置IP地址
IP地址为你的服务器公网IP地址,端口号为已开放的端口号,如果用的是阿里云,需要设置端口号,否则无法进行连接。端口号设置示例如下:
1.2.服务端的完整代码Server
package socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author :hly
* @github :github.com/SiriusHly
* @blog :blog.csdn.net/Sirius_hly
* @date :2018/8/19
*/
public class Server implements Runnable {
public static final String IP = "123.XX.219.XX";
public static final int PORT = 5000;
@Override
public void run() {
ServerSocket serverSocket = null;
try {
//绑定端口
serverSocket = new ServerSocket(PORT);
System.out.println("等待连接");
Socket socket = serverSocket.accept();
System.out.println("连接成功");
//获取输入流
//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataInputStream in = new DataInputStream(socket.getInputStream());
//获取输出流
//BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//读取信息
System.out.println("读取1");
String str = in.readUTF();
System.out.println("读取2");
System.out.println("服务器接收到的消息为:"+str);
//发送信息给客户端
out.writeUTF("1");
out.flush();
socket.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread myThread = new Thread(new Server());
myThread.start();
}
}
1.3.readLine注意事项
如果传输单条数据,输入流可能无法使得可以接收到数据,代码如下:
//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine()
上面的代码接收不到数据,因为in.readLine是一个阻塞方法,只要没有断开连接,就会一直进行等待,而不是返回null,当断开连接后,就会出现异常,通常需要用一定的分隔符,socket适用麻烦,下面是其源码:
String readLine(boolean