网络编程-Tcp传输1

我的梦境 提交于 2019-12-04 20:33:30
一次简单的Tcp 传输import java.io.*;
import java.net.*;
public class Practice_1 {

    public static void main(String[] args) throws Exception   {
        // TODO Auto-generated method stub

        new Thread(new TcpClient()).start();
        new Thread(new TcpSer()).start();
        
    }
}

class TcpClient implements Runnable
{
    public void run()
    {
        try {
            method();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public void method() throws Exception
    {
        //1:创建Socket 、指定端口
        Socket s = new Socket("199.234.8.53",10003);
        
        // 2:为了发送数据、应该获取socket中的输出流 。
        OutputStream out = s.getOutputStream();    
        
        out.write("tcp ge men lai le ".getBytes());

        s.close();
    }
}
class TcpSer implements Runnable
{
    public void run()
    {
        try {
            method();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void method() throws Exception
    {
        ServerSocket ss = new ServerSocket(10003);
        Socket s = ss.accept();
        
        String ip = s.getInetAddress().getHostAddress();
        System.out.println("ip::"+ip);
        InputStream in = s.getInputStream();
        
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        
        System.out.println(new String(buf,0,len));
        s.close();
        ss.close();
        
    }
}


/*客户端:  
 * 1:创建Socket 、指定端口
 * 2:为了发送数据、应该获取socket中的输出流 。
 * 
 * 
 * 
 * 服务端:
 * 1、建立服务端的socket服务、serverSocket()、并且监听一个端口
 * 2、获取连接过来的客户端对象
 *    通过ServerSocket的Accept方法。 没有连接就会等待、因为这个方法是阻塞式的。
 * 3、客户端如果发过来数据,那么服务端要使用对应的客户端对象、并获取到该客户端对象的读取流来读取、并作操作
 * 4、关闭服务端(可选操作)。
 */

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!