JAVA网络编程TCP案例

413人浏览 / 0人评论
服务端
import java.net.*;
import java.io.*;
 
public class TCPServerSocket {
    public static void main(String[] args) throws Exception{
        String data = "";
        //while (true) {
            try{
                ServerSocket ss = new ServerSocket(8888);
                Socket s = ss.accept();
                InputStream in = s.getInputStream();
                int len = 0;
                byte[] buff = new byte[1024];
                while((len = in.read(buff)) > 0) {
                    data += new String(buff,0,len);
                }
            } catch (Exception e){
                System.out.println("Exception");
            }
            System.out.println(data);
        //}
         
    }
}
客户端
import java.net.*;
import java.io.*;
public class TCPSocket{
    public static void main(String[] args) throws Exception{
        int port = 8888;
        String ip = "127.0.0.1";
        //InetAddress address = InetAddress.getByAddress(stringToByte(ip));
        InetAddress address = InetAddress.getByName("localhost");
        Socket socket = new Socket(address, port);
        OutputStream out = socket.getOutputStream();
        String data = "hello";
        byte buff[] = data.getBytes();
        out.write(buff,0,buff.length);
        out.flush();
        socket.close();
    }
 
    public static byte[] stringToByte (String ip){
        String[] strArr = ip.split(".");
        byte[] IPArr = new byte[4];
         
        System.out.println(strArr.length);
 
        for(int i = 0; i < 4; i++){
            IPArr[i] = (byte)Integer.parseInt(strArr[i]); 
        }
 
        return IPArr;
    }
}