闲着写了个简单java的socket编程,无语了,这么简单的程序都写不出来了,代码如下:
==================================================================================
Server(服务器端):
package remember;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket ss;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Server() {
try {
ss = new ServerSocket(33333);
System.out.println("========亲,服务器已经启动===========");
while (true) {
socket = ss.accept();
String RemoteIP = socket.getInetAddress().getHostName();
String RemotePort = "" + socket.getLocalPort();
System.out.println(RemoteIP+" "+ RemotePort);
out = new PrintWriter(socket.getOutputStream(), true);
out.print("消息已经收到了");
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String line=in.readLine();
System.out.print(line);
in.close();
out.close();
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("wrong");
}
}
public static void main(String[] args) {
new Server();
}
}
Client(客户端):
package remember;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
private Socket socket;
private BufferedReader in;
private PrintWriter out; public Client() {
try {
System.out.println("Try to Connect to 127.0.0.1:33333"); socket = new Socket("127.0.0.1",33333);
System.out.println("The Server Connected!");
System.out.println("Please enter some Character:"); BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(socket.getOutputStream(),true); out.print(line.readLine());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine()); out.close(); in.close();
socket.close();
}catch(IOException e) { out.println("Wrong");
} }
public static void main(String[] args) {
new Client();
} }
5555555555555555,以前也这样写的,怎么忘了啊。研究半天总结如下:
----------------------------------------------------------------------------------------------------------------------------------
服务端的PrintWriter一定要写成out.println,不能写成out.print。
客户端的PrintWriter可写成out.println也可以写成out.print(但如果写成out.print就只能发数据接收不到数据了)。
哎呀,纠结了半天,终于写好了。希望能帮到和我一样的人,所以就分享下,本人原创。