这个程序我试过在自己的电脑上是可以连接的,但是我吧服务端发给别人运行,我都是让别人先运行服务端然后才启动客户端的,但是两台电脑之间就是连接不上,这是为什么?
具体代码如下
```java
class Client{
public static void main(String[] args) throws IOException {
InetAddress inetAddress=InetAddress.getByName("fe80::ac2e:7f79:cbf5:c18f%17");//本机与给本机建立链接
//指定要传输地端口号
Socket socket=new Socket(inetAddress, 8899);
//对外进行数据传输
OutputStream outputStream = socket.getOutputStream();
outputStream.write("能看见嘛,看见的话给我回复一下".getBytes());
socket.shutdownOutput();//关闭传输
//接收服务端信息
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
String line;
while ((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
//关闭资源
outputStream.close();
socket.close();
}
}
class Service{
public static void main(String[] args) throws IOException {
System.out.println("服务端开启,等待客户端连接......");
ServerSocket socket=new ServerSocket(8899);//指定当前端口号
Socket accept = socket.accept();//表示可以接收客户端
System.out.println("与"+socket.getInetAddress().getHostAddress()+"用户连接成功!");
InputStream inputStream = accept.getInputStream();
InputStreamReader reader=new InputStreamReader(inputStream);//转换流
BufferedReader bufferedReader=new BufferedReader(reader);//字符流
String line;
while ((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
//给客户端回复
OutputStream outputStream = accept.getOutputStream();
BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream);
bufferedOutputStream.write("客户端你好,信息已接收到!".getBytes());
//关闭流
bufferedOutputStream.flush();
bufferedOutputStream.close();
bufferedReader.close();
}
}
```