TCP Socekt 交互例子

程序功能:

开启服务端 -> 客户端发送消息到服务端 -> 服务端打印接收到的消息 -> 服务端返回一个消息给客户端 -> 客户端接收服务端返回的消息并打印


package com.zf.test05;

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

public class Server04 {
	

	public static void main(String[] args) throws Exception {
		
		final String message = "server message";
		
		ServerSocket serverSocket = new ServerSocket(8888) ;
		
		System.out.println("server start success...");
		
		Socket client = serverSocket.accept();

		InputStream is = client.getInputStream() ;
		

		// receive msg
		ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
		byte[] buf = new byte[1];
		int len = -1;
		while((len = is.read(buf)) != -1){
			System.out.println("client:read msg once");
			baos.write(buf , 0 , len);
			baos.flush();
		}
		
		byte[] receiveDatas = baos.toByteArray() ;
		System.out.printf("server:message:%s%n"
				,new String(receiveDatas));     
		
		//send msg
		OutputStream os = client.getOutputStream() ;
		os.write(message.getBytes());
		os.flush();   
		client.shutdownOutput();  //如果不调用该方法,另一端的read方法讲一直阻塞。
		System.out.println("server:send message success...");
		
		client.close();
		serverSocket.close();
	}

}

package com.zf.test05;

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

public class Client04 {

	public static void main(String[] args) throws Exception {
		
		final String message = "client message";
		
		Socket socket = new Socket("127.0.0.1" , 8888);
		OutputStream os = socket.getOutputStream() ;
		
		//send msg
		os.write(message.getBytes());  
		os.flush();
		socket.shutdownOutput();	//如果不调用该方法,另一端的read方法讲一直阻塞。
		System.out.println("client:send message success!");
		
		// receive msg
		InputStream is = socket.getInputStream() ;
		ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
		byte[] buf = new byte[1];
		int len = -1;
		
		while((len = is.read(buf)) != -1){
			System.out.println("client:read msg once");
			baos.write(buf , 0 , len);
			baos.flush();
		}
		
		
		byte[] receiveDatas = baos.toByteArray() ;
		
		System.out.printf("client:message:%s%n" ,
				new String(receiveDatas));      
		socket.close();
		
		
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值