socket java 客户端_用Java 的socket实现客户端的功能

该博客展示了如何使用Java实现一个简单的TCP服务器和客户端进行通信。服务器监听特定端口,接收并打印客户端发送的消息,当接收到特定指令('byte')时关闭连接。客户端则读取用户输入,发送到服务器并接收回应。测试结果显示了双方交互的过程。
摘要由CSDN通过智能技术生成

展开全部

//服务端程序:

import java.io.*;

import java.net.*;

public class TCPServer {

public static void main(String[] args) throws IOException {

new TCPServer().init();

}

@SuppressWarnings("static-access")

private void init() throws IOException{

@SuppressWarnings("resource")

ServerSocket server = new ServerSocket(1000);

Socket client = null;

while(true){

try {

client = server.accept();

BufferedInputStream bis = new BufferedInputStream(client.getInputStream());

byte[] b = new byte[1024];

int len = 0;

String message = "";

while((len=bis.read(b))!=-1){

message = new String(b,0,len);

System.out.print("客户端:32313133353236313431303231363533e78988e69d8331333335333761"+client.getInetAddress().getLocalHost().getHostAddress()+"发来消息:" + message);

if("byte".equals(message.trim()))

client.close();

PrintWriter pw = new PrintWriter(client.getOutputStream(),true);

pw.println(message);

}

} catch (Exception e) {

System.err.println("客户端:"+client.getInetAddress().getLocalHost().getHostAddress()+" 已断开连接!");

}

}

}

}//客户端程序:

import java.io.*;

import java.net.Socket;

public class TCPClient implements Runnable{

public static void main(String[] args) throws IOException {

new TCPClient().init();

}

private void init() throws IOException{

@SuppressWarnings("resource")

final Socket client = new Socket("127.0.0.1",1000);

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

String send = "";

while(true){

send = in.readLine();

PrintWriter out = new PrintWriter(client.getOutputStream(),true);

if(!"byte".equals(send.trim()))

out.println(send);

else{

out.println(send);

System.exit(0);

}

new Thread(new TCPClient(){

@SuppressWarnings("static-access")

public void run(){

try {

BufferedInputStream bis = new BufferedInputStream(client.getInputStream());

byte[] b = new byte[1024];

int len = 0;

while((len=bis.read(b))!=-1){

System.out.println("服务器:" +client.getInetAddress().getLocalHost().getHostAddress()+"发来消息:"+new String(b,0,len).trim());

}

} catch (IOException e) {

System.err.println("连接服务器失败!");

}

}

}).start();

}

}

public void run() {}

}

//服务器测试结果:

客户端:192.168.0.200发来消息:001 byte

客户端:192.168.0.200发来消息:byte

客户端:192.168.0.200 已断开连接!

客户端:192.168.0.200发来消息:adasd

客户端:192.168.0.200 已断开连接!

//客户端测试结果:

---001号客户端--

001 byte

服务器:192.168.0.200发来消息:001 byte

byte //001礼貌说跟服务器说byte

---002号客户端--

adasd //002客户端直接关闭程序

服务器:192.168.0.200发来消息:adasd

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值