利用Java编写聊天程序
- 首先计算机网络有两种传输层协议:TCP(面向连接),UDP(面向无连接)。今天就介绍基于这两种协议的聊天程序。
先查明自己电脑的主机名
右键我的电脑-->属性
一、基于UDP的聊天程序
1.基于UDP的发送端
package cn.com;
/**
* 基于UDP
* 聊天发送端
*/
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class Send {
public static void main(String[] args) throws IOException {
@SuppressWarnings("resource")
DatagramSocket ds = new DatagramSocket();
Scanner sc = new Scanner(System.in);
String line = null;
while ((line = sc.nextLine()) != null) {
byte[] buf = line.getBytes();
int length = buf.length;
InetAddress address = InetAddress.g