雪糕小可爱
2016-04-12 12:48
public class Server {
public static void main(String[] args) {
try {
//1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口
ServerSocket serverSocket=new ServerSocket(8888);
//2.调用accept方法开始监听,等待客户端的连接
System.out.println("******服务器即将启动,等待客户端的连接*****");
Socket socket=serverSocket.accept();
//3.获取输入流,用来读取客户端信息
InputStream is=socket.getInputStream();//字节输入流
//为了提高读取的性能,将字节流包装编程字符流
InputStreamReader isr=new InputStreamReader(is);
//用缓冲的方式进行读取
BufferedReader bf=new BufferedReader(isr);//为输入流添加缓冲
String info=null;
while((info=bf.readLine())!=null){//循环读取客户端的信息
System.out.println("我是服务器,客户端说:"+info);
}
socket.shutdownInput();//关闭输入流
//4.关闭资源
bf.close();
isr.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Client {
public static void main(String[] args) {
try {
//1.创建客户端Socket,指定服务器地址和端口
Socket socket=new Socket("localhost",8888);
//2.获取输入流,向服务器发送信息
OutputStream os=socket.getOutputStream();//字节输出流
PrintWriter pw=new PrintWriter(os);//将输出流包装秤打印流
pw.write("用户名:admin;密码:123");
pw.flush();//刷新数据
socket.shutdownOutput();//关闭输出流
//3.关闭其他的资源
pw.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
应该是你电脑没有映射localhost, 把localhost改成真实ip。
同问,也是这问题
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at com.internet.Server.main(Server.java:15)
请问如何解决的
我遇到了同样的问题,怎么解决的啊?
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at Server.main(Server.java:22)
Java Socket应用---通信是这样练成的
125013 学习 · 590 问题
相似问题