TCP简单程序

Posted 静! 非淡泊无以明志,非宁静无以致远!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TCP简单程序相关的知识,希望对你有一定的参考价值。

服务器段:

package com.dcz.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
	
	public static void main(String[] args) {
		
		String data = "你好啊,socket 世界!";
		
		// 端口
		int port = 17001;
		ServerSocket serverSocket = null;
		
		try {
			serverSocket = new ServerSocket(port);
			System.out.println("服务端已经准备就绪......");
			
			boolean isAccept = true;
			while (isAccept) {
				
				Socket client = serverSocket.accept();
				InetAddress inetAddress = client.getInetAddress();
				System.out.println("客户端ip:" + inetAddress);
				
				OutputStream clientOutputStream = client.getOutputStream();
				clientOutputStream.write(data.getBytes());
				clientOutputStream.close();
			}
			serverSocket.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

  

客户端代码:

package com.dcz.socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.commons.io.output.ByteArrayOutputStream;

public class TcpClient {
	
	public static void main(String[] args) {
		
		String address = "127.0.0.1";
		int port = 17001;
		Socket client = null;
		try {
			client =  new Socket(address, port);
			InputStream serverInputStream = client.getInputStream();
			
			 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			
			byte[] buffer = new byte[1024];
			while((serverInputStream.read(buffer, 0, buffer.length)) != -1){
				byteArrayOutputStream.write(buffer, 0, buffer.length);
			}
			
			byte[] data = byteArrayOutputStream.toByteArray();
			
			System.out.println(new String(data, "utf-8"));
			
			
			byteArrayOutputStream.close();
			client.close();
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		

		
	}

}

  

以上是关于TCP简单程序的主要内容,如果未能解决你的问题,请参考以下文章

在android中显示隐藏片段

Android - 如何录制简单的声音片段?

NodeJS编写简单TCP/UDP端口代理转发服务

在PaddlePaddle中的Notebook代码片段

为啥这段代码会泄露? (简单的代码片段)

java代码在片段活动中不起作用