求教,代码如下
- /**
- * Tcp服务端
- * @author AdamJY
- *
- */
- public class TcpServer {
- public static void main(String[] args) throws Exception
- {
- // 建立服务端socket服务。并监听一个端口。
- ServerSocket ss = new ServerSocket(10006);
-
- // 通过accept方法获取请求连接的客户端对象。
- while(true)
- {
- // 阻塞式
- Socket s = ss.accept();
-
- String ip = s.getInetAddress().getHostAddress();
- System.out.println(ip+" connected successfully.");
-
- // 获取客户端发送过来的数据,那么要使用客户端对象的读取流来读取数据。
- InputStream in = s.getInputStream();
-
- byte[] buf = new byte[1024];
- int len = in.read(buf);
-
- System.out.println(new String(buf,0,len));
- //得到输出流,向客户端写数据
- OutputStream os = s.getOutputStream();
- os.write("Hi, client, I'm server!".getBytes());
-
- s.close();//关闭客户端.
- }
- //ss.close();
- }
- }
复制代码
- /**
- * Tcp客户端
- * @author AdamJY
- *
- */
- public class TcpClient {
- public static void main(String[] args)throws Exception{
- //建立socket对象,指定服务端的
- Socket s = new Socket(InetAddress.getLocalHost(),10006);
- //得到输出流,向服务端写数据
- OutputStream out = s.getOutputStream();
- out.write("Hi, server, I'm client.".getBytes());
- //得到输入流,读取服务端返回的数据
- InputStream in = s.getInputStream();
- byte[] buf = new byte[1024];
- int len = in.read(buf);
- System.out.println(new String(buf,0,len));
- s.close();
- }
- }
复制代码
异常信息:
Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at com.itheima.TcpServer.main(TcpServer.java:17) |