package cn.com.socket;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务端同时读和写
* @author Administrator
*
*/
public class ServerDemo1 {
public static void main(String[] args) throws IOException {
//为了简单起见,所有的异常信息都往外抛
int port = 8899;
//定义一个ServerSocket监听在端口8899上
ServerSocket server = new ServerSocket(port);
//server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
Socket socket = server.accept();
//跟客户端建立好连接之后,我们就可以获取socket的InputStream,并从中读取客户端发过来的信息了。
Reader reader = new InputStreamReader(socket.getInputStream());
char chars[] = new char[64];
int len;
StringBuilder sb = new StringBuilder();
String temp;
int index;
while ((len=reader.read(chars)) != -1) {
temp = new String(chars, 0, len);
if ((index = temp.indexOf("eof")) != -1) {//遇到eof时就结束接收
sb.append(temp.substring(0, index));
break;
}
sb.append(temp);
}
System.out.println("我是服务器,客户端说: " + sb);
//读完后写一句
Writer writer = new OutputStreamWriter(socket.getOutputStream());
writer.write("Hello Client.");
writer.flush();
writer.close();
reader.close();
socket.close();
server.close();
}
}
package cn.com.socket;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 客户端同时读和写
* @author Administrator
*
*/
public class ClientDemo1 {
public static void main(String[] args) throws UnknownHostException, IOException {
//为了简单起见,所有的异常都直接往外抛
String host = "localHost"; //要连接的服务端IP地址
int port = 8899; //要连接的服务端对应的监听端口
//与服务端建立连接
Socket client = new Socket(host, port);
//建立连接后就可以往服务端写数据了
Writer writer = new OutputStreamWriter(client.getOutputStream());
writer.write("Hello Server.");
writer.write("eof");
writer.flush();
//写完以后进行读操作
Reader reader = new InputStreamReader(client.getInputStream());
char chars[] = new char[64];
int len;
StringBuffer sb = new StringBuffer();
String temp;
int index;
while ((len=reader.read(chars)) != -1) {
temp = new String(chars, 0, len);
if ((index = temp.indexOf("eof")) != -1) {
sb.append(temp.substring(0, index));
break;
}
sb.append(new String(chars, 0, len));
}
System.out.println("我是客户端,服务器说: " + sb);
writer.close();
reader.close();
client.close();
}
}
|