首页 > 编程语言 > 详细

JAVA-Socker网络编程

时间:2021-05-25 22:27:52      阅读:27      评论:0      收藏:0      [点我收藏+]

 

内容出处https://study.163.com/course/courseMain.htm?courseId=1209171838

 

客户端源代码

package my;

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

public class test
{

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

        //一个Socket代表一路连接
        Socket sock = new Socket();
        
        //连接至服务器
        sock.connect(new InetSocketAddress("192.168.1.101", 2019));
        
        //InputStream用于接收数据,OutputStream用于发送数据
        InputStream inputStream = sock.getInputStream();
        OutputStream outputStream = sock.getOutputStream();
        
        //发送数据
        String outputMsg = "Hello";
        byte[] outputData = outputMsg.getBytes("UTF-8");
        outputStream.write(outputData);
        System.out.println(">>: " + outputMsg);
        
        //接收数据
        byte[] inputData = new byte[4000];
        int n = inputStream.read(inputData);
        String inputMsg = new String(inputData, 0, n, "UTF-8");
        System.out.println("<<:" + inputMsg);
        
        //关闭连接
        sock.close();
    }

}

 

服务器源代码

package my;

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

public class test {

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

        //建立服务器,服务于2019端口
        ServerSocket serverSock = new ServerSocket(2019);
        System.out.println("服务器启动,等待连接...");
        while(true)
        {
            //监听请求,阻塞等待,直接有客户端发起连接...
            Socket conn = serverSock.accept();
            
            //从连接里得到输入输出流
            //InputStream:可以读取客户端发来的数据
            //OutputStream:可以发送数据给客户端
            InputStream inputStream = conn.getInputStream();
            OutputStream outputStream = conn.getOutputStream();
            
            //接收数据
            byte[] inputData = new byte[4000];
            int n = inputStream.read(inputData);
            if(n<=0)
            {
                conn.close();
                continue;
            }
            
            //发送数据
            String inputMsg = new String(inputData, 0, n, "UTF-8");
            System.out.println("GOT:" + inputMsg);
            
            String outputMsg = "Welcome!";
            byte[] outputData = outputMsg.getBytes("UTF-8");
            outputStream.write(outputData);
            System.out.println("ECHO:" + outputMsg + "\n");
            
            //关闭连接
            conn.close();        
        }
        
        
    }

}

 

演示

技术分享图片

 

程序员阿飞

2021年5月25日

JAVA-Socker网络编程

原文:https://www.cnblogs.com/nxopen2018/p/14810377.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!