简单的socket,连接不到阿里云的服务器。
package socket_guest;
import java.io.OutputStream;
import java.net.Socket;
public class socket
{
public static void main(String[] args) throws Exception
{
String host="/**/";
int port=2000;
Socket socket=new Socket(host,port);
OutputStream outputStream=socket.getOutputStream();
String message="amessage";
socket.getOutputStream().write(message.getBytes("UTF-8"));
outputStream.close();
socket.close();
}
}
package socket;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class receive
{
public static void main(String[] args) throws Exception
{
int port=2000;
ServerSocket server=new ServerSocket(port);
Socket socket=server.accept();
InputStream inputStream =socket.getInputStream();
byte[] bytes=new byte[1024];
int len;
StringBuilder sb=new StringBuilder();
while((len=inputStream.read(bytes))!=-1)
{
sb.append(new String(bytes,0,len,"UTF-8"));
}
System.out.println("get message from client: " + sb);
inputStream.close();
socket.close();
server.close();
}
}
代码本身是没有问题的,连接不上阿里云。
查明原因:阿里云默认关闭端口
需要在安全设置添加。
选择自定义并设置打开的端口范围即可。