socket案例二

编写一个网络应用程序,有客户端与服务器端,客户端向服务器端发送一个字符串,服务器收到该字符串后将其打印到命令行上,然后向客户端返回该字符串的长度,最后,客户端输出服务器端返回的该字符串的长度。

           

              

服务器端

package com.hrtx.test;

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

/**
* 服务器端:响应请求
*
*
*
@author jiqinlin
*
*/
public class ServerTest {
public static void main(String args[]) throws Exception {
ServerSocket ss
=new ServerSocket(8888);
//说明服务器启动成功,正在等待客户端请求连接
System.out.println("Listening...");
Socket socket
=ss.accept();
//说明有客户端请求连接
System.out.println("Client Connected...");

InputStream in
=socket.getInputStream();
OutputStream out
=socket.getOutputStream();
byte[] buffer=new byte[100];

//返回客户端请求的字符串长度
int length=in.read(buffer);
//返回客户端请求的字符串
String content=new String(buffer, 0, length);
System.out.println(
"read from client: "+content);

//向客户端返回该字符串的长度
int len=content.length();
out.write(String.valueOf(len).getBytes());

//关闭流
in.close();
out.close();
socket.close();
}
}

                

              

客户端        

package com.hrtx.test;

import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* 客户端:发送请求
*
*
@author jiqinlin
*
*/
public class ClientTest {
public static void main(String[] args) throws Exception {
Socket socket
= new Socket("192.168.2.105", 8888);
InputStream in
=socket.getInputStream();
OutputStream out
=socket.getOutputStream();

//向服务器端发送请求
String content="林计钦";
out.write(content.getBytes());

//从服务器端返回信息
byte[] buffer=new byte[1024];
int length=in.read(buffer);
String str
=new String(buffer, 0, length);
System.out.println(
"string's length: "+str.length());

//关闭流
in.close();
out.close();
socket.close();
}
}
posted on 2011-06-24 21:52  Ruthless  阅读(1798)  评论(0编辑  收藏  举报