欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

socket

程序员文章站 2022-04-24 11:41:07
...

server端



package socket.demo;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class SocketServer {
    public static void main(String args[]){
        int port=5533;
        try {
            ServerSocket server=new ServerSocket(port);
            Socket socket=server.accept();
            System.out.println("server waiting");
            InputStream input=socket.getInputStream();
            byte[] bytes=new byte[1024];
            int length;
            StringBuilder sbBuilder=new StringBuilder();
            while((length=input.read(bytes))!=-1)   {
                sbBuilder.append(new String(bytes,0,length,"UTF-8"));
            }
            System.out.println("get msg from client"+sbBuilder);
            
            OutputStream out=socket.getOutputStream();
            out.write("i'm server,got your msg".getBytes());
            input.close();
            out.close();
            socket.close();
            server.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}

客户端:写完后,要立即关闭输出流(outputstream)

/**
* @author jy
*/
package socket.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;


public class SocketClient {

   /**
    * @param args
    *<p>Description: </p>  
    */
   public static void main(String[] args) {

       int port=5533;
       String ip="127.0.0.1";
       try {
           Socket socket=new Socket(ip,port);
           String msg="hello";
           OutputStream out=socket.getOutputStream();
           out.write(msg.getBytes());
           socket.shutdownOutput();
           
           InputStream in=socket.getInputStream();
           byte[] bytes=new byte[1024];
           StringBuilder sbBuilder=new StringBuilder();
           int len;
           while((len=in.read(bytes))!=-1){
               sbBuilder.append(new String(bytes,0,len,"UTF-8"));
           }
           System.out.println("client got msg from server"+sbBuilder);
           //out.close();
           in.close();
           socket.close();
       } catch (UnknownHostException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }

}