我做了一个客户端发送消息到服务器端,socket能连接上,但发送不了数据,不知为什么
------解决方案--------------------
代码?
------解决方案--------------------
我也学java不是很久! 下面是我写的代码! 另外楼主的注释过多,有许多JDK提供方法没必要进注释
- Java code
// 客户端TCPClientimport java.io.*;import java.net.*;import java.util.Scanner;public class TCPClient { private static int sort=3434; private static String host="localhost"; //本机ip地址 public static void main(String avg[]){ Scanner input = new Scanner(System.in); BufferedReader br=null; BufferedWriter wr=null; Socket s =null; try{ while(true){ System.out.print("客户端说:"); String line = input.nextLine(); if(line.equals("byb")) break; s=new Socket(TCPClient.host,TCPClient.sort); wr =new BufferedWriter(new OutputStreamWriter( s.getOutputStream())); wr.write(line); wr.close(); s.close(); //关闭会话 try { //暂停一会儿! Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } s=new Socket(TCPClient.host,TCPClient.sort); br =new BufferedReader(new InputStreamReader( s.getInputStream())); System.out.print("接收端:"); int next=0; StringBuffer li=new StringBuffer(); while((next=br.read()) != -1) li.append((char)next); System.out.println(new String(li.toString())); br.close(); s.close(); 关闭会话! } }catch(UnknownHostException e){ System.out.println("服务器连接失败"); e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } }}
------解决方案--------------------
wr.write(line);后面加wr.flush();