服务器端的java代码

package com.aaa.servet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;//导入java.net包,用于网络通讯
import java.net.Socket;
/**
 * 这种是基于TCP的案例。
 * @author teayear
 *
 */
public class ServerSocketTest {
	public static void main(String[] args) {
		System.out.println("...启动TCP Socket服务器...");
		//1.初始化服务端Socket并绑定端口为8888
		try {
			ServerSocket serverSocket=new ServerSocket(8888);//需要添加try/catch块
			//2.等待客户端的连接
			Socket socket=serverSocket.accept();
			//3.获取输入流,通过socket对象流,传递给缓冲字符流进行读取;
			BufferedReader bufferReader=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
			//4.读取一行数据;
//			String str=bufferReader.readLine();
			String str;
			//4.1升级,通过循环升级接受信息;
			while((str=bufferReader.readLine())!=null){
				//5.输出打印
				System.out.println(str);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

效果如下:

TCP面向连接的socket通信_TCP

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSocket {
	public static void main(String[] args) {
		//1.创建socket对象,建立到服务i端的连接;
		try {
			Socket socket=new Socket("127.0.0.1",8888);
			//2.通过缓冲输出流,包装下socket对象的输出字节流,进行写操作;
			BufferedWriter bufferWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"GBK"));

			//通过标准输入流获取字符流;
			BufferedReader bufferReader=new BufferedReader(new InputStreamReader(System.in,"GBK"));
			//循环升级;
			while(true){
				String str=bufferReader.readLine();
				bufferWriter.write(str);
				bufferWriter.write("\n");
				//3.2还需要将缓冲中的内容放到socket
				bufferWriter.flush();
			}
			//4.注意一定要有关闭连接;
//			socket.shutdownOutput();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

TCP面向连接的socket通信_socket_02

在服务器端会显示:

TCP面向连接的socket通信_UDP通信_03