자바 소켓 통신 및 TCP/UDP 구현

44048 단어 자바
지난번 에 socket 을 접 했 을 때 도 대학 3 학년 때 귀 를 긁 고 볼 을 긁 었 을 때,2 년 이 지난 오늘 에 도 그것 을 사 용 했 던 것 을 기억 하 세 요.그러면 Socket 을 조직 방송 을 실현 하 는 것 을 기록 하 세 요.
TcpServer
public class TcpServer {
	private static boolean isruning = true;

	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(5583);
			while (isruning) {
				//   
				Socket socket = serverSocket.accept();
				System.out
						.println("     (" + socket.getInetAddress() + ")  。。");
				OutputStream stream = socket.getOutputStream();
				OutputStreamWriter writer = new OutputStreamWriter(stream);
				writer.write("hello socket!");
				writer.flush();
				writer.close();
				System.out
						.println("   (" + socket.getInetAddress() + ")    。。");
			}
			serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


TcpClient
public class TcpClient {

	public static void main(String[] args) {
		String host = "localhost"; //        IP  
		int port = 5583; //               
		try {
			//         
			Socket client = new Socket(host, port);
			InputStream inputStream = client.getInputStream();
			InputStreamReader reader = new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(reader);
			String message = bufferedReader.readLine();
			System.out.println(message);
			bufferedReader.close();
			client.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}


UdpSend
public class UdpSend {
	public static void main(String[] args) {
		MulticastSocket socket;
		try {
			socket = new MulticastSocket(8842);
			socket.setTimeToLive(1);
			InetAddress address = InetAddress.getByName("233.0.0.0");
			socket.joinGroup(address);
			byte[] buf = "hello world!".getBytes();
			DatagramPacket p = new DatagramPacket(buf, buf.length, address,
					8842);
			socket.send(p);
			System.out.println("      ");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

UdpReceive
public class UdpReceive {

	public static void main(String[] args) {
		MulticastSocket socket;
		try {
			socket = new MulticastSocket(8842);
			socket.setTimeToLive(1);
			InetAddress address = InetAddress.getByName("233.0.0.0");
			socket.joinGroup(address);
			byte[] buf = new byte[3000];
			DatagramPacket p = new DatagramPacket(buf, buf.length);
			socket.receive(p);
			System.out.println("   " + p.getAddress() + "     "
					+ new String(p.getData()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

2019 년 1 월 4 일 16:43:00 업데이트
나중에 이 루어 진 것 은 이전 버 전보 다 더 잘 붙 여 졌 다.
public class cfg {
    public static String ip = "192.168.0.106";
    public static int port = 8030;
}

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

public class Client {
    public static void main(String[] args) {
        try {
            //         
            Socket client = new Socket(cfg.ip, cfg.port);
            System.out.println("    !");
            new Send(client).start();
            new Recerver(client).start();
            //socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Recerver extends Thread {
    Socket socket;

    public Recerver(Socket client) {
        this.socket = client;
    }

    @Override
    public void run() {
        super.run();
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            for (; ; ) {
                DataInputStream stream = new DataInputStream(inputStream);
                int head = -1;
                while ((head = stream.read()) != 0xff) {
                    System.out.print("bad data");
                }
                System.out.print("head:" + head);
                int len = stream.readInt();
                byte[] data = new byte[len];
                stream.read(data, 0, len);
                String str = new String(data, Charset.forName("utf-8"));
                System.out.println(socket.getInetAddress() + ":" + str);
            }
        } catch (IOException e) {
            System.out.println(socket.getInetAddress() + "     ");
        }
    }
}

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Scanner;

public class Send extends Thread {
    Socket socket;

    public Send(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        super.run();
        try {
            OutputStream out = socket.getOutputStream();
            Scanner scanner = new Scanner(System.in);
            for (; ; ) {
                String msg = scanner.nextLine();
                byte[] content = msg.getBytes("utf-8");
                ByteBuffer byteBuffer = ByteBuffer.allocate(content.length + 5);
                byteBuffer.put((byte) 0xff);
                byteBuffer.putInt(content.length);
                byteBuffer.put(content);
                out.write(byteBuffer.array());
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class Server {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(cfg.port);
            System.out.println("    :" + InetAddress.getLocalHost().getHostAddress() + ":" + serverSocket.getLocalPort());
            for (; ; ) {
                //   
                Socket socket = serverSocket.accept();
                System.out
                        .println("     (" + socket.getInetAddress() + ")  ");
                new Send(socket).start();
                new Recerver(socket).start();
            }
            //serverSocket.close();
        } catch (IOException e) {
            System.out.print("     :" + e.getMessage());
        }
    }
}

좋은 웹페이지 즐겨찾기