下面是tcp的Server代码块
/**
* Socket的服务端
*
*当前程序有弊端 只能为1个客户端提供服务
*
*/
public class MyServerSocket01 {
/**
* 程序的执行入口
*
* @param args 传递的参数
*/
public static void main(String[] args) throws Exception {
//创建服务端的Socket对象
ServerSocket serverSocket = new ServerSocket();
//服务端绑定端口
serverSocket.bind(new InetSocketAddress(8899));
//监听客户端的连接(阻塞的方法),返回的是当前连接到服务器的客户端的对象
Socket socket = serverSocket.accept();
System.out.println("有客户端" + socket.getRemoteSocketAddress() + "连接到服务器了.....");
InputStream inputStream = socket.getInputStream();
//读数据
byte[] buf = new byte[2];
int len;
//调用read方法返回阻塞,当没有数据时会阻塞,并不会返回-1
while ((len = inputStream.read(buf)) != -1) {
String str = new String(buf, 0, len);
System.out.println(str);
}
}
}
下面是客户端
//创建Socket的客户端的对象
Socket socket = new Socket();
//连接服务器,当然客户端也可以绑定端口,如果不绑定端口,则每次随机分配一个没有使用的端口
socket.connect(new InetSocketAddress("127.0.0.1", 8899));
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello".getBytes());
outputStream.flush();
outputStream.close();
socket.close();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
当然.客户端也可以用相应的软件来
下面是UDP的服务器端代码
//创建udp的接收端
DatagramSocket ds = new DatagramSocket(8899);
byte[] data = new byte[1024];
DatagramPacket dp = new DatagramPacket(data, 0, data.length);
ds.receive(dp);
System.out.println();
System.out.println(new String(data,0, dp.getLength()));
ds.close();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
客户端代码如下:
//创建udp的客户端
DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.connect(new InetSocketAddress("localhost", 8899));
byte[] data = "hello".getBytes();
DatagramPacket dp = new DatagramPacket(data, 0, data.length);
datagramSocket.send(dp);
System.out.println("发送成功...");
datagramSocket.close();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8