Java套接字编程

//TCP-Client
public class Client
{
    static Socket socket = null;
    static OutputStream output = null;

    public static void main(String[] args) throws IOException
    {
       try
       {
           InetAddress inet = InetAddress.getByName("127.0.0.1");//获取本地IP

           socket = new Socket(inet,6666);//插入连接到Ip为inet,端口为6666的套接字

           output = socket.getOutputStream();//获取套接字的输出流

           output.write("Hello World!".getBytes());//向流中写入字节信息

       }
       catch (Exception e)
       {
           System.out.println(e.getMessage());
       }
       finally//关闭资源
       {
           if(socket != null)
           {
               try
               {
                   socket.close();
               }
               catch (Exception e)
               {
                   e.printStackTrace();
               }
           }

           if(output != null)
           {
               try
               {
                   output.close();
               }
               catch (Exception e)
               {
                   e.printStackTrace();
               }
           }

       }

    }
}
//TCP-Server
public class Server

{
    static Socket socket = null;
    static ServerSocket server = null;
    static InputStream input = null;
    static ByteArrayOutputStream baos = null;

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

            server = new ServerSocket(6666);//设置服务器监听端口号

            socket = server.accept();//阻塞式监听:从此接口的套接字接收

            input = socket.getInputStream();//获取输入流

            baos = new ByteArrayOutputStream();//连接从buffer读入和向console输出的输出流
            int length = 0;
            byte[] buffer = new byte[1024];//TCP面向字节流

            while((length = input.read(buffer))!= -1)//read方法返回存进buffer的字节数
                baos.write(buffer,0,length);//write方法返回buffer的字节存入baos中


            System.out.println(baos.toString());



        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if(socket != null)
            {
                try
                {
                    socket.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

            if(baos != null)
            {
                try
                {
                    socket.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            if(input != null)
            {
                try
                {
                    socket.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

            if(server != null)
            {
                try
                {
                    socket.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

        }

    }
}
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

//send线程
public class send implements Runnable
{
    DatagramSocket socket = null;
    int port;//port that send to

    public send(int port) throws Exception { //construcotor in which a socket is             
                                             // established
        this.port = port;
        socket = new DatagramSocket();
    }

    @Override
    public void run()
    {
        byte[] buffer = new byte[1024]; //to save string
        Scanner input = new Scanner(System.in);
        while (true)
        {
            String message = input.nextLine(); //read from console
            buffer = message.getBytes(StandardCharsets.UTF_8);//assign the byte array of the string read from console
            try {
                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port));//creat the packet used to transit to the localhost with correspodning port
                socket.send(packet); //send to it
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("sended");

            if(message.equals("exit"))
                break;

        }

        socket.close();

    }
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;

//receive
public class receive implements Runnable
{
    DatagramSocket socket = null;
    int port;

    public receive(int port) throws Exception {
        this.port = port;
        socket = new DatagramSocket(port);//creat socket used to receive
    }

    @Override
    public void run()
    {
        byte[] buffer = new byte[1024];
        //store the packet data into buffer
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

        while (true)
        {
            try {
                socket.receive(packet); //receive from socket to the local packet
            } catch (Exception e) {
                e.printStackTrace();
            }
            //utilize the String constructor to converse type
            String message = new String(packet.getData(),0,packet.getLength());
            System.out.println("received: " + message);

            if (message.equals("exit"))
                break;
        }
        socket.close();
    }
}
/* 
    two class to execute the send thread and receive thread

*/

public class Driver1
{
    public static void main(String[] args) throws Exception {
        new Thread(new receive(6666)).start();
        new Thread(new send(6667)).start();
    }
}


public class Driver2
{
    public static void main(String[] args) throws Exception {
        new Thread(new receive(6667)).start();
        new Thread(new send(6666)).start();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DefinedBySaint

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值