首页 > 代码库 > TCP编程

TCP编程

package wabgki;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TestSever {
    public static void main(String[] args) {
        try {
            //1.创建SerceSocket
            ServerSocket server=new ServerSocket(8888);
            System.out.println("等待连接");
            //2.等待客户端的连接请求 此方法是阻塞方法
            Socket s=server.accept();
            
            //3.获得输入流
            BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())) ;
            String str=br.readLine();
            System.out.println("收到了"+str);
            System.out.println("连接成功");
            s.close();
            server.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
package wabgki;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class KeHu {


    public static void main(String[] args) throws IOException {

      InetAddress a=InetAddress.getLocalHost();
        Socket b=new Socket(a,8888);
        PrintWriter pw=new PrintWriter(b.getOutputStream());
        pw.println("好久不见,别来无恙");
        pw.flush();    
        System.out.println("客户端连接成功");
        b.close();

    }

}

 

TCP编程