C/C++教程

基本的socket编程

本文主要是介绍基本的socket编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

# 客户端

 

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class SocketClient {

	public static void main(String[] args) throws Exception {
		//获取用户输入的数据
		Scanner input = new Scanner(System.in);
		System.out.println("请输入数据:");
		String inputData = input.nextLine();

		//开启一个Socket端口
		Socket sc = new Socket("127.0.0.1", 6666);
		OutputStream os = sc.getOutputStream();
		os.write(inputData.getBytes());

		//获取服务端回传的数据
		InputStream is = sc.getInputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		len = is.read(buffer);
		String getData = new String(buffer, 0, len);
		System.out.println("从服务端获取的数据:" + getData);
		//是否流
		is.close();
		os.close();
		sc.close();
	}

}

# 服务器端

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketSer {

	public static void main(String[] args) throws Exception {

		ServerSocket ss = new ServerSocket(6666);
		boolean flag = true;
		while (flag) {
			//接收客户端的请求
			System.out.println("监听客户端的数据:");
			Socket sc = ss.accept();
			InputStream is = sc.getInputStream();
			byte[] buffer = new byte[1024];
			int len = -1;
			len = is.read(buffer);
			String getData = new String(buffer, 0, len);
			System.out.println("从客户端获取的数据:" + getData);
			//业务处理 大小写转化
			String outPutData = getData.toUpperCase();

			//向客户端写数据
			OutputStream os = sc.getOutputStream();
			os.write(outPutData.getBytes("UTF-8"));

			//释放资源
			os.close();
			is.close();
			sc.close();
		}
		ss.close();
	}

}

这篇关于基本的socket编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!