Socket 简单的相互通讯

TCPEchoServer
package com.mz.xx.code.atest;

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

public class TCPEchoServer {

private static final int BUFSIZE = 32;

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

int servPort = 7788;

ServerSocket servSock = new ServerSocket(servPort);

int recvMsgSize;
byte[] receiveBuf = new byte[BUFSIZE];

while(true){
Socket clntSock = servSock.accept();

SocketAddress clientAddress = clntSock.getRemoteSocketAddress();
System.out.println("Handling client at" + clientAddress);

InputStream in = clntSock.getInputStream();
OutputStream out = clntSock.getOutputStream();

while((recvMsgSize = in.read(receiveBuf))!=-1){
System.out.println("IN...");
out.write(receiveBuf,0,recvMsgSize);
out.flush();
System.out.println("Sended:"+new String(receiveBuf)+"\t"+recvMsgSize);
}
clntSock.close();
}

}

}


TCPEchoClient
package com.mz.xx.code.atest;

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

public class TCPEchoClient {

public static void main(String[] args) throws UnknownHostException,
IOException {
String server = "localhost";
byte[] data = "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ ".getBytes();

int servPort = 7788;

Socket socket = new Socket(server, servPort);
System.out.println("Connected to server...sending echo string");

InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();

out.write(data);

int totalBytesRcvd = 0;
int bytesRcvd;

byte[] dataArray = new byte[data.length];


/**
* 以前学习socket,对于消息的读取也就用一个read().最近在学一本socke编程的书籍,书中这样写到:
* TCP协议并不能确定在read() 和 write() 方法中所发送信息的界限,也就是说,虽然我们只用勒一个
* write()方法来发送回馈字符串,回馈服务器也可以从多个块中接受该信息。即使回馈字符串在服务器
* 上存在于一个块中,在返回的时候,也可能被TCP协议分割成多个部分。对于初学者来说,最常见的错误
* 就是认为由一个write()方法发送的数据总是会由一个read()方法来接受。
*
*/
while (totalBytesRcvd < dataArray.length) {
if ((bytesRcvd = in.read(dataArray, totalBytesRcvd, data.length
- totalBytesRcvd)) == -1)
throw new SocketException("Connection closed prematurely");
totalBytesRcvd += bytesRcvd;
}//data array is full
System.out.println("Received: " + new String(dataArray)+"\t"+dataArray.length);
socket.close();
}
}


Java TCP/IP Socket 源码:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值