//ServerSocket
import java.io.*;
import java.net.*;
public class TcpServer {
public static void main(String[] args) throws Exception{
ServerSocket server = new ServerSocket(10003);
Socket client = server.accept();
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
byte[] by = new byte[1024];
int len = 0;
String msg = null;
while((len=is.read(by))!=-1){
msg = new String(by,0,len);
System.out.println("来自"+client.getInetAddress().getHostAddress()+"客户端的消息:"+msg);
if("886".equals(msg))
break;
os.write(getPrint(msg));
}
client.close();
}
private static byte[] getPrint(String msg){
return msg.getBytes();
}
}
//Socket
import java.io.*;
import java.net.*;
public class TcpClient {
public static void main(String[] args) throws Exception{
Socket sk = new Socket("localhost",10003);
OutputStream os = sk.getOutputStream();
InputStream is = sk.getInputStream();
os.write(getPrint());
byte[] by = new byte[1024];
int len = 0;
while((len=is.read(by))!=-1){
System.out.println("来自"+sk.getInetAddress().getHostAddress()+"服务器的消息:"+new String(by,0,len));
os.write(getPrint());
}
sk.close();
}
private static byte[] getPrint()throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String msg = in.readLine();
return msg.getBytes();
}
}
//一下是输出结果:
来自127.0.0.1客户端的消息:Hello
来自127.0.0.1客户端的消息:eee
来自127.0.0.1客户端的消息:886
//客户端:
Hello
来自127.0.0.1服务器的消息:Hello
eee
来自127.0.0.1服务器的消息:eee
886
提示:如果提问者想使用DataInputStream可以自行替换掉即可。
这个是个例子,你参考一下吧