Java中ServerSocket与Socket简单的使用

这是一个客户端与服务器端的简单交互代码,用于理解之间的数据传递。
废话不多说,直接上代码。

客户端

package com.quaint.scoket;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
/**
 * 客户端简要代码
 * @author Quaint
 * @date 2018年11月18日
 */
public class Client {

	public static void main(String[] args) {
		try {
			//建立连接
			Socket socket = new Socket("127.0.0.1",7777);
			//发送数据
			OutputStream os = socket.getOutputStream();
			Scanner in = new Scanner(System.in);
			System.out.println("你想往服务器发表什么?");
			String msg = in.nextLine();
			os.write(msg.getBytes());
			//接收数据
			InputStream is = socket.getInputStream();
			byte[] b = new byte[1024];
			int n = is.read(b);
			//输出服务器回复数据
			System.out.println("服务器回复:" + new String(b,0,n));
			is.close();
			in.close();
			os.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace(); 
		}
	}

}

服务器端

package com.quaint.scoket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * 服务器端简要代码
 * @author Quaint
 * @date 2018年11月18日
 */
public class Service {

	public static void main(String[] args) {

		try {
			//创建一个服务器端
			ServerSocket ss = new ServerSocket(7777);
			System.out.println("等待客户端连接...");
			//等待客户端连接
			Socket s = ss.accept();
			//连接之后接受客户端发来的消息
			InputStream is = s.getInputStream();
			byte[] b = new byte[1024];
			int n = is.read(b);
			System.out.println(new String(b,0,n));
			//返回给客户端消息
			OutputStream os = s.getOutputStream();
			os.write("服务器收到你的消息。".getBytes());
			s.close();
			ss.close();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
}

猜你喜欢

转载自blog.csdn.net/quaint_csdn/article/details/84197838