客户端程序:
import java.net.*;
import java.io.*;
public class DaytimeClient 
{
public static final int SERVICE_PORT = 13; public static void main(String args[])
{
// Check for hostname parameter
if (args.length != 1)
{
System.out.println ("Syntax - DaytimeClient host");
return;
} // 读取服务器名称
String hostname = args[0];
try
{
//获取一个服务器
Socket daytime = new Socket (hostname, SERVICE_PORT); System.out.println ("Connection established"); //设置超时时间
daytime.setSoTimeout ( 2000 ); //向服务器发送信息
OutputStream sender = daytime.getOutputStream();
PrintStream pout = new PrintStream (sender);
pout.print("i love you");
sender.flush();

//读取服务器传送信息
BufferedReader reader = new BufferedReader ( 
new InputStreamReader(daytime.getInputStream())); System.out.println ("Results : " + reader.readLine()); //关闭连接
daytime.close();
}
catch (IOException ioe)
{
System.err.println ("Error " + ioe);
}
}
}
服务器端程序:
import java.net.*;
import java.io.*;public class DaytimeServer 
{
public static final int SERVICE_PORT = 13; public static void main(String args[])
{
try
{
// 绑定端口
ServerSocket server = new ServerSocket (SERVICE_PORT); System.out.println ("Daytime service started"); for (;;)
{
// 获取一个客户端
Socket nextClient = server.accept(); // 显示客户端信息
System.out.println ("Received request from " +
nextClient.getInetAddress() + ":" + nextClient.getPort() ); //向客户端发送信息
OutputStream out = nextClient.getOutputStream();
PrintStream pout = new PrintStream (out); pout.print( "hello,i got you!"); out.flush();

//接受客户端信息
BufferedReader reciever = new BufferedReader ( 
new InputStreamReader(nextClient.getInputStream()));
System.out.println ("接受信息 : " + reciever.readLine()); // 关闭与客户端的连接
nextClient.close();
}
}
catch (BindException be)
{
System.err.println ("Service already running on port " + SERVICE_PORT );
}
catch (IOException ioe)
{
System.err.println ("I/O error - " + ioe);
}
}
}
如果是服务器和客户端只作单一发送或者接受信息程序就可以运行,但是同时既发送有接收的话,程序会产生异常,希望前辈们指点!

解决方案 »

  1.   

    靠 用这样吗? 同志: "跪求各位前辈的回答"你没一个socket新建立一个thread 在public void run() 里面接受 readLine()就行了. 如果发送信息呢就要建立一个界面 弄一个swing 的 textInput 那种东西进去 每次按发送按钮的时候 就 socket.write(xx);就行了.你说的其实是阻塞的问题 java.nio可以解决这些 不过得用selector channel什么的 你去书店里多看看书 还是可以学会的 不过要有耐心和锻炼.祝你成功 但是下次不要再说什么 "跪求各位前辈的回答" 你是个人 问个问题至于这样吗 你说问题很急或者说的有些诚意就成了 不必要这样了 我们大家都回给你回答的 :)好好学习 天天向上吧 :)