udpclient.java

来自「简单通信程序」· Java 代码 · 共 31 行

JAVA
31
字号
import java.net.*;
import java.io.*;
import java.util.*;

public class UDPClient {
	public static final int DEFAULT_PORT = 8989;
	public static final int DEFAULT_SERVER_PORT = 12345;

	public static void main( String[] args ) {
		Scanner in = new Scanner( System.in );

		try {
			DatagramSocket ds = new DatagramSocket( DEFAULT_PORT );
			InetAddress target = InetAddress.getLocalHost();
			while ( true ) {
				String messageToSend = in.nextLine();
				byte[] buf = messageToSend.getBytes();
				DatagramPacket ip = new DatagramPacket( buf, buf.length, target, DEFAULT_SERVER_PORT );
				ds.send( ip );
				if ( messageToSend.equals("exit") ) {
					break;
				}
			}
		} catch ( SocketException e ) {
			e.printStackTrace();
		} catch ( IOException e ) {
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?