本帖最后由 沈佳龙 于 2012-10-10 18:13 编辑
客户端代码:
package com.sjl.ServerAndClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client1 {
public static void main(String[] args) {
Socket mysocket = null;
DataInputStream in = null;
DataOutputStream out = null;
String str = null;
try {
mysocket = new Socket("localhost",1420);
} catch (IOException e) {System.out.println("无法连接");}
try{
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
for(int i=1;i<=100;i++){
str = in.readUTF();
out.writeInt(i);
System.out.println("客户端收到:"+str);
Thread.sleep(500);
}
}catch (Exception e){}
}
}
服务器端代码:
package com.sjl.ServerAndClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server1 {
public static void main(String[] args) {
ServerSocket server= null;
Socket you = null;
DataInputStream in = null;
DataOutputStream out = null;
try{
server = new ServerSocket(1420);
you = server.accept();
}catch (IOException e1){
System.out.println("连接不上");
}
try{
in = new DataInputStream(you.getInputStream());
out = new DataOutputStream(you.getOutputStream());
int m = 0;
while(true){
m = in.readInt();
out.writeUTF("你说的数字对应的字符为"+(char)m);
System.out.println("服务器收到:"+m);
Thread.sleep(500);
}
}catch(IOException e){
System.out.println(""+e);
}catch(InterruptedException e2){}
}
}
客户端发送一个数值,服务器回复一个ASCII值。 不知道问题出在哪,控制台没有输出。。。 |