java Socket编程(一)

本文提供了一个简单的Java网络编程示例,包括服务器端与客户端的交互过程。服务器监听10000端口接收客户端发来的消息,并打印接收到的内容。客户端连接服务器并发送字符串“helloworld”。该示例展示了如何使用Java进行基本的网络通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务器端
package com.robert.view;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerClient {

	public static void main(String[] args) {
		ServerSocket server = null;
		Socket  socket = null;
		InputStream inputStream = null;
		BufferedInputStream bis = null;
		DataInputStream dis = null;
		try {
			server = new ServerSocket(10000);
			socket = server.accept();
			inputStream = socket.getInputStream();
			bis = new BufferedInputStream(inputStream);
			dis = new DataInputStream(bis);
			System.out.println(dis.readUTF());
		} catch (IOException e) {
			e.printStackTrace();
		}finally
		{
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}


客户端

package com.robert.view;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class CustomerClient {


	public static void main(String[] args) {
		OutputStream outputStream = null;
		BufferedOutputStream bos = null;
		DataOutputStream dos = null;
		try {
			Socket socket = new Socket("localhost",10000);
			outputStream = socket.getOutputStream();
			bos = new BufferedOutputStream(outputStream);
			dos = new DataOutputStream(bos);
			dos.writeUTF("hello world");	
			dos.flush();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally
		{
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值