Java Socket编程??简单的问候服务实现
作者:网络转载 发布时间:[ 2012/12/4 10:06:23 ] 推荐标签:
客户端代码如下:
package com.gloomyfish.socket.tutorial.two;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
public class HelloClient {
private int clientNumber;
private SocketAddress address;
public HelloClient(int clientNum) {
clientNumber = clientNum;
}
public void setupClients(String serverHostName, int port) throws IOException {
address = new InetSocketAddress(serverHostName, port);
for(int i=0; i<clientNumber; i++) {
System.out.println();
System.out.println("start client No. " + (i+1));
Socket socket = new Socket();
socket.connect(address);
DataInputStream bufferedReader = new DataInputStream(socket.getInputStream());
byte[] cbuff = new byte[256];
char[] charBuff = new char[256];
int size = 0;
while( (size = bufferedReader.read(cbuff))> 0) {
convertByteToChar(cbuff, charBuff, size);
System.out.println(charBuff);
}
bufferedReader.close();
socket.close();
}
}
private void convertByteToChar(byte[] cbuff, char[] charBuff, int size) {
for(int i=0; i<charBuff.length; i++) {
if(i < size) {
charBuff[i] = (char)cbuff[i];
} else {
charBuff[i] = ' ';
}
}
}
public static void main(String[] args) {
try {
HelloClient client = new HelloClient(10);
client.setupClients("localhost", 9999);
} catch (IOException e) {
e.printStackTrace();
}
}
}
启动10个客户端去连接服务器端,接受到服务器端问候以后客户端关闭连接。
特别提示:一定要初始化缓冲区charBuff
程序运行结果:
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11