TCPEchoServer
TCPEchoClient
Java TCP/IP Socket 源码:
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 源码: