客户端代码:
package net;
import java.net.*;
import java.io.*;
public class socketclient {
public static void main(String[] args) {
Socket s = null;
InputStream is = null;
DataInputStream d = null;
OutputStream os = null;
DataOutputStream ds = null;
try {
s = new Socket("127.0.0.1", 1555);
is = s.getInputStream();
d = new DataInputStream(is);
os = s.getOutputStream();
ds = new DataOutputStream(os);
System.out.println(d.readUTF() + " from " + s.getPort());
String content = null;
while (true) {
content = new BufferedReader(new InputStreamReader(System.in))
.readLine();
ds.writeUTF("port# " + s.getLocalPort() + " says " + content
+ " to " + s.getPort());
ds.flush();
if (content.equalsIgnoreCase("Bye"))
break;
}
} catch (ConnectException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ds.close();
os.close();
d.close();
is.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务器端代码:
package net;
import java.net.*;
import java.io.*;
public class socketserver {
public static void main(String[] args) {
Socket s = null;
OutputStream out = null;
DataOutputStream ds = null;
InputStream is = null;
DataInputStream d = null;
try {
ServerSocket ss = new ServerSocket(1555);
s = ss.accept();
out = s.getOutputStream();
ds = new DataOutputStream(out);
is = s.getInputStream();
d = new DataInputStream(is);
} catch (IOException e) {
e.printStackTrace();
}
try {
String content = null;
ds.writeUTF("Hello " + s.getInetAddress() + " port#"
+ s.getPort());
ds.flush();
while (true) {
content = d.readUTF();
System.out.println(content);
if (content.equalsIgnoreCase("Bye"))
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ds.close();
out.close();
d.close();
is.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我有一个已经实现的,没弄错的话也是支持传送文件的,当然是局域网,不过是当年上学时练手的,还是有不少bug。
自已写吧,慢慢的就写出来了,先把界面做出来,再一步步的实现,很快就搞定了的