Java Socket通讯小Demo升级版

第一块 客户端代码:

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

public class TcpIpTest {

	public static void main(String[] args) {
		int i = 9090;
		String s = new String("127.0.0.1");
		String content = new String("hello,I am client");
		Client client = new Client(s, content, i);
		client.start();

	}
}

class Client {

	int i; // 用于确定端口号
	String content; // 用于确定通讯的字符串内容
	String str = null; // 用于指定Ip地址
	Socket socket = null;
	OutputStream os = null;

	// 构造器 分别用于初始化 IP地址, 传输字符串内容,端口号
	Client(String str, String content, int i) {
		this.str = str;
		this.content = content;
		this.i = i;

	}

	// 构造器 分别用于初始化 IP地址, 端口号
	Client(String str, int i) {
		this.str = str;
		// this.content=content;
		this.i = i;
	}

	// 自定义的客户端启动方法
	void start() {
		try {
			socket = new Socket(InetAddress.getByName(str), i); // 创建客户端socket对象
			os = socket.getOutputStream(); // 获得输出流
			os.write(content.getBytes()); // 输出内容,因为并将content字符串转换为字节数组
			socket.shutdownOutput(); // 传输完毕后告诉 自己传输完毕了
		} catch (Exception e) {

			e.printStackTrace();

		} finally {
			try {
				if (os != null) // 关闭稀有资源流
					os.close();
			} catch (IOException e1) {

				e1.printStackTrace();
			}
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {

				e.printStackTrace();
			}
		}
	}

}


第二块 服务端代码

package Likeyong.com;

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

//服务端代码

public class ServerTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Server server = new Server(9090);
		server.start();
	}

}

class Server {
	int i; // 用于确定端口号
	ServerSocket ss = null;
	InputStream is = null;
	Socket s = null;

	// 构造器
	Server(int i) {
		this.i = i;
	}

	void start() {
		try {
			ss = new ServerSocket(i);

			s = ss.accept();
			// ss.setSoTimeout(2500);
			is = s.getInputStream();
			int len;
			byte[] b = new byte[20];
			while ((len = is.read(b)) != -1) {
				String s1 = new String(b, 0, len);
				System.out.println(s1);
			}
		} catch (IOException e) {

			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (s != null) {
				try {
					s.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
			if (ss != null) {
				try {
					ss.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值