求一个JAVA Scoket编程的例子

来源:百度知道 编辑:UC知道 时间:2024/09/23 03:52:02
求一个JAVA Scoket编程的例子,要求写一个Server,接收客户端的信息并产生相应发回给客户端

服务器端:
//host.java
import java.io.*;//BufferedReader
import java.net.*;
import java.text.*;
import java.util.*;
public class host
{
public static void main(String args[])
{
String reces=null;
String ret=null;
int len;
Socket s;
OutputStream os;
InputStream is;
byte[] rece = new byte[1000];
try
{
ServerSocket ss = new ServerSocket(9527); //服务器的套接字,端口为9527
while(true)
{
s = ss.accept();
os = s.getOutputStream();
is = s.getInputStream();
len= is.read(rece);//接受客户端消息
if(len!=0)
reces=new String(rece, 0, len);
System.out.println(reces);
ret="I'am the host,I received you words at ("+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ").format(new Date())+")";
os.write(ret.getBytes());//返回给客户端的欢迎信息
is.close();
os.close();
s.